Using NPM packages without Webpack

Viewed 3796

I am used to using NPM packages with Webpack, but I'm wondering how you're supposed to use NPM packages without Webpack. I know how to install packages. I just don't know how to use them, since you can't just import modules in plain js.

4 Answers

Webpack compiles a bunch of javascript files and combines them into a single one for web distribution. NPM downloads javascript files through packages.

Here's some scenarios where you might use NPM without webpack

  1. You are doing Node.js server-side javascript development. There's no webpack here
  2. You are using a webpack alternative like rollup or browserify
  3. You directly do anything else with the files npm downloads. Maybe you concatenate, throw them in a Makefile or maybe you expose node_modules directly to the world and reference their full paths directly.

Most of my web and server-side development is without webpack.

Why you can't import in plain js?

If you correctly define the package entry point like "main": "dist/index.js", "module": "dist/index.js",

Those files can be plain ES6 javascript with named exports or export default, and you can import them after intalling your package with regular import.

You don't need webpack nor babel to make an mpm module. Just put in any folder the files you want to distribute, specifying the main entry point and export elements on that file.

Now... in an angular or react application for example, they may install your component and will use babel and webpack to first transpile your component to ES5 with babel, and then bundle your code together with the rest of their app using webpack.

For front-end, not node.js but still NPM modules.

HTML can import directly ES6 modules but the file must be in .mjs format and provide export default, Module.exports in regular .js file wont't work. This is not a common thing and you'll run into problems if there are subdependencies that don't use ES6 modules. If you find a module that supports it. i.e. some-module

npm install some-module

And in the same directory next to node_modules create index.html pointing straight to the modular bundle

<h1>I'm HTML</h1>
<script type="module">
  import SomeModule from './node_modules/some-module/bundle.mjs';
  const mod = new SomeModule();
  mod.doStuff();
</script>

Here's an article about this https://medium.com/passpill-project/files-with-mjs-extension-for-javascript-modules-ced195d7c84a

npm init

To create a package.json file

npm install --save <package>

To install a package and save it in the package.json file

Related