使用 babel 从 node_modules 导入模块但失败

import a module from node_modules with babel but failed

我用es6写了一个模块发布到npm,想用在别的项目中,所以我这样输入:

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 加载器配置:

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

当我尝试导入一个不是来自 node_modules 的模块时,babel 运行良好。但是从 node_modules 导入一个模块,babel 好像不行?

参见the babel docs

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

通常期望 node_modules 中的模块已经提前转译,所以它们不会被 Babel 处理。如果您不这样做,那么您需要告诉它可以处理哪些文件。 ignore 允许。

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

一般来说,上传到 npm 的包应该是预编译的,这样用户就可以收到正常的 JS,不需要构建步骤。为此使用 npm prepublish

但是,如果您使用的是 webpack,则可以在 webpack 配置中指定一个 exclude 函数(参见 webpack docs):

module: {
  loaders: [{
    test: /.jsx?$/,
    loader: 'babel-loader',
    exclude(file) {
      if (file.startsWith(__dirname + '/node_modules/this-package-is-es6')) {
        return false;
      }
      return file.startsWith(__dirname + '/node_modules');
    },

如果你直接使用 babel,you can write a similar ignore function in the require hook

您可以使用 https://www.npmjs.com/package/babel-node-modules 对于这种情况

npm install --save-dev babel-node-modules
require('babel-node-modules')([
  'helloworld' // add an array of module names here 
]);

然后它将列出的模块编译为其他文件