Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to consume npm package with es6 module via Webpack and 6to5?

Tags:

Let's say I want to use Immutable in my project (or any given npm package). I have npm installed it, so it is in node_modules. Of course, it has CommonJS exports there. I, however, want to use es6 modules in my project.

I am using Webpack to compile it all together, with the 6to5-loader to deal with es6 module syntax.

In my source file, I say import Immutable from 'immutable'; --- but this causes a problem because the es6 import is looking for an es6 default to have been exported, which isn't the case (for Immutable or probably almost any other npm package). The compiled code ends up looking like this: var Immutable = require('immutable')["default"]; --- which of course throws an error, since there is no default property to find.

Can I consume the npm packages with es6 modules?

like image 260
davidtheclark Avatar asked Dec 04 '14 23:12

davidtheclark


People also ask

How do I use ES6 with webpack?

Create your scripts in package. json : "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "build": "webpack", "start": "webpack-dev-server --open" }, Run npm run build and npm start .

Does webpack use ES6 modules?

This section covers all methods available in code compiled with webpack. When using webpack to bundle your application, you can pick from a variety of module syntax styles including ES6, CommonJS, and AMD.


2 Answers

Babel.js contributor here. You're looking for the following:

import * as Immutable from 'immutable'; // compiles to: var Immutable = require('immutable'); 

Interactive demo

Note: This is with either the common or commonInterop modules option. For others, see: https://babeljs.io/docs/usage/modules/

like image 88
James Kyle Avatar answered Oct 13 '22 00:10

James Kyle


Just figured it out. (The solution is tool-specific --- but es6 modules only exist now insofar as they are tool-enabled, so I think that's enough of an "answer".)

6to5's default module transpilation uses the common option, which results in the very problem I griped about above. But there is another option: commonInterop --- which must have been built to deal with exactly the situation I'm dealing with. See https://6to5.github.io/modules.html#common-interop

So three cheers for 6to5.

like image 40
davidtheclark Avatar answered Oct 13 '22 01:10

davidtheclark