web-dev-qa-db-ja.com

babelを使用してnode_modulesからモジュールをインポートしましたが失敗しました

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が機能しないようです。

18
Leo Gao

バベルのドキュメント を参照してください:

注:デフォルトでは、node_modulesに必要なものはすべて無視されます。これは、無視する正規表現を渡すことでオーバーライドできます。

一般的に期待されるのは、node_modulesは事前に変換されているため、Babelによって処理されません。それを行わない場合は、処理できるファイルを通知する必要があります。 ignoreはそれを許可します。

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

通常、npmにアップロードされたパッケージはプリコンパイルする必要があるため、ユーザーは通常のJSを受け取り、ビルド手順を必要としません。使用する npm prepublish このため。

ただし、webpackを使用している場合は、exclude関数をwebpack構成で指定できます( 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を直接使用している場合、 requireフックに同様のignore関数を記述できます

4
Wilfred Hughes

この場合は 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 
]);

次に、リストされたモジュールを他のファイルとしてコンパイルします

1
Nedudi