Importing NPM Modules to the Web as ES6 Modules
In this post, I want to share the method that I used to import nearly any NPM module into a front-end project using ES6 Modules.
Join the DZone community and get the full member experience.Join For Free
I’ve been working on a way to make it easier to push content into my static site and it’s been a fun little exercise that I will share more in another post. In this post, I want to share the
rollup config that I used to import nearly any NPM module into a front-end project using ES6 Modules.
I needed a quick way to import a simple module
I couldn’t find a lot of guidance on what to do here, so I went to experiment and this solution is the solution I came across:
- Create a file that imports the NPM module I needed.
module.exports = require('get-urls');This module will be what converted to ES6 style.
- Create a
- Imports the node globals, and built-ins.
- Resolves all npm modules required for my usage of this module.
- Pass the results through the
commonjsplugin so that it’s now in ES6 Module format.
- Compress the output, because it’s huge.
- Include the bundled file in your project and rejoice.
I think there are probably better ways than this, the output for what is a relatively simple function is huge (70kb), but it now means that I can use modules from NPM directly in my page.
Published at DZone with permission of Paul Kinlan, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.