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
578 views
in Technique[技术] by (71.8m points)

reactjs - import a module from node_modules with babel but failed

I wrote a module with es6 and publish to the npm, I want to use it in another project, so I type like this:

import {ActionButton} from 'rcomponents'

But it didn't work:

D:githublog
ode_modules
componentssrcactionButton.jsx:1
(function (exports, require, module, __filename, __dirname) { import React fro
                                                              ^^^^^^
SyntaxError: Unexpected reserved word
    at exports.runInThisContext (vm.js:73:16)
    at Module._compile (module.js:443:25)
    at Module._extensions..js (module.js:478:10)
    at Object.require.extensions.(anonymous function) [as .jsx] (D:githublog
node_modulesabel
ode_modulesabel-corelibapi
egister
ode.js:214:7)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at D:githublog
ode_modules
componentssrcindex.js:3:19
    at Object.<anonymous> (D:githublog
ode_modules
componentssrcindex.js:
7:3)

Here is my js loader configuration in webpack:

{ test: /.jsx?$/, loader: `babel?cacheDirectory=${babelCache}` }

When I try to import a module which is not from node_modules, babel works good. But import a module from node_modules, babel seems not work?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

See the babel docs:

NOTE: By default all requires to node_modules will be ignored. You can override this by passing an ignore regex.

Generally the expectation is that modules in node_modules will already have been transpiled ahead of time, so they are not processed by Babel. If you will not be doing that, then you need to tell it what files it can process. ignore allows that.

require("babel/register")({
    // Ignore everything in node_modules except node_modules/rcomponents.
    ignore: /node_modules/(?!rcomponents)/
});

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

...