Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
368 views
in Technique[技术] by (71.8m points)

javascript - Babelify throws ParseError on import a module from node_modules

I'm working with Babelify and Browserify. Also, I'm using ES6 style module features by node module system.

I would like to put all my own modules into node_modules/libs.

For instance:

test.js in node_modules/libs

export default () => {
  console.log('Hello');
};

main.js (will be compiled to bundle.js)

import test from 'libs/test';

test();

After that, I have compiled the above codes to bundle.js with this command:

browserify -t babelify main.js -o bundle.js

But unfortunately, I have got some error:

export default () => {
^

ParseError: 'import' and 'export' may appear only with 'sourceType: module'

Directory structure:

[test]
  `-- node_modules
  │ `-- libs
  │  `-- test.js
  `-- main.js

But, when own modules not in node_modules like this:

[test]
  `-- libs
  │ `-- test.js
  `-- main.js

Then, it works fine. How can I use the ES6 style modules with babelify in node_modules?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

That is how Browserify transforms work, transforms only have an effect directly in the module that is being referenced.

If you want a module in node_modules to have a transform, you'd need to add a package.json to that module and add babelify as a transform for that module too. e.g.

"browserify": {
  "transform": [
    "babelify"
  ]
},

inside your package.json plus babelify as a dependency will tell browserify to run the babelify transform on any file inside that module.

Having libs be a folder in node_modules is however probably a bad idea. Generally that folder would have true standalone modules in it. I'd generally say that if the folder can't be taken and reused elsewhere, then it shouldn't be in node_modules.

Update

For Babel v6, which was recently released, you will also need to specify which transformations you would like to perform on your code. For that, I would recommend creating a .babelrc file in your root directory to configure Babel.

{
  "presets": ["es2015"]
}

and

npm install --save-dev babel-preset-es2015

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...