Home > front end >  How to import from an npm installed module
How to import from an npm installed module

Time:07-26

I have a webpage that I'd someday like to host. I've installed a few packages in the dev folder using npm, and they appear in the node_modules sub-folder. I'd like to use these packages in a js module, but the import statement doesn't work as the docs lead me to expect.

Taking gsap as an example:

npm install gsap

Given that, and html that looks like this:

index.html

<html>
  <head>
  </head>

<body>
  <div id="app"></div>
</body>
<script type="module" src="./index.js"></script>
</html>

I expect I should be able to have a js module that looks like this:

index.js

// per https://greensock.com/docs/v3/Installation
import { gsap } from "gsap"; // ERROR HERE

console.log(gsap); 

Uncaught TypeError: Failed to resolve module specifier "gsap". Relative references must start with either "/", "./", or "../".

Placing a/, or a ./ or any other combinations of paths I've tried produces a not found error. The only thing I can get to work is this, which I figured out by digging around in the node_modules folder...

import { gsap } from "/node_modules/gsap/gsap-core.js"; // this works, but yikes
console.log(gsap); 

I must be doing something wrong to have to know that path and file name. I have a few packages I'd like to use, and I hope to not have to investigate each one to find where the actual module file resides.

Can somebody set me straight?

CodePudding user response:

 import { gsap } from "/node_modules/gsap/gsap-core.js"; // this works, but yikes

There's nothing particularly yikes about that in principle.

Browsers are not Node.js. They do not work the same way as Node.js. They cannot go rummaging about your server's file system in order to look for a module based on just its name.

You have to give them a URL to the JS file you want to import.


What is yikes about this is that you are exposing your entire node_modules directory over HTTP, and you probably don't want to do that.

A typical approach to using modules installed via NPM in the browser is to use a bundler such as Webpack or Parcel which will take all the modules your code depends on and bundle them up in to a distribution for sending to the browser (while doing optimisations such as tree shaking).

  • Related