user13822269
user13822269

Reputation:

How to import nodejs modules in vanilla Javascript file

how does one import nodejs modules in a vanilla Javascript file? In other words, how can I use my nodejs modules in a vanilla javascript file for frontend scripting?

Upvotes: 26

Views: 29060

Answers (5)

Magnus Lind Oxlund
Magnus Lind Oxlund

Reputation: 381

To just import an npm package as a vanilla Javascript module, you can source it from skypack.dev.

Let's say you're interested in the popular D3 data visualization library, which is distributed on npm under the handle d3.

Here's how you would load it in HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <script type="module">
        import * as foo from 'https://cdn.skypack.dev/d3';
        console.log(foo); // Module {Adder: class Adder, Delaunay: class Delaunay, …}
    </script>
</head>
</html>

Upvotes: 1

4N0M41Y
4N0M41Y

Reputation: 342

use browserify to build your nodejs code so that it gets read by front end.

Upvotes: 0

Yoel Duran
Yoel Duran

Reputation: 429

If you don't want to use the CDN, you can create a path with Node.js to get what you want from "node_modules"

in node.js

app.get('/jquery', (req, res) => {
    res.sendFile(path.join(__dirname, 'node_modules/jquery/dist/jquery.min.js'))
})

in html

<script src="/jquery"></script>

Upvotes: 0

Nikhil Singh
Nikhil Singh

Reputation: 1610

These modules are packaged using a tool called npm. You can use module loaders or bundlers like Browserify or Webpack to use npm modules in the frontend.

This might help you

Upvotes: 19

Luke Storry
Luke Storry

Reputation: 6752

You can include them via a CDN, like unpkg or cdnjs. It lets you easily load any file from any package using a URL like: unpkg.com/:package@:version/:file

For example, to get d3 on your page, you could add a script tag like so:

<script src="https://unpkg.com/[email protected]/dist/d3.min.js" />

More Info

Upvotes: 14

Related Questions