使用babel从node_modules导入模块但失败 [英] import a module from node_modules with babel but failed
问题描述
我用es6编写了一个模块,然后发布到npm,我想在另一个项目中使用它,所以我这样输入:
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'
但这没用:
D:\github\blog\node_modules\rcomponents\src\actionButton.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:\github\blog\
node_modules\babel\node_modules\babel-core\lib\api\register\node.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:\github\blog\node_modules\rcomponents\src\index.js:3:19
at Object.<anonymous> (D:\github\blog\node_modules\rcomponents\src\index.js:
7:3)
这是我在webpack中的js加载程序配置:
Here is my js loader configuration in webpack:
{ test: /\.jsx?$/, loader: `babel?cacheDirectory=${babelCache}` }
当我尝试导入不是来自node_modules
的模块时,babel效果很好.但是从node_modules
导入模块,babel似乎不起作用?
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?
推荐答案
请参见 babel文档:
注意:默认情况下,对node_modules的所有要求都将被忽略.您可以通过传递忽略正则表达式来覆盖它.
NOTE: By default all requires to node_modules will be ignored. You can override this by passing an ignore regex.
通常期望node_modules
中的模块已经提前进行了转译,因此Babel不会对其进行处理.如果您不打算这样做,则需要告诉它可以处理哪些文件. ignore
允许.
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)/
});
这篇关于使用babel从node_modules导入模块但失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!