简体   繁体   中英

How to import from an npm installed module

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?

 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM