使用 babel-jest 的自定义转换器时出现意外的令牌导入

Unexpected token import when using custom transformer of babel-jest

当我 运行 npm test (jest --watch) 时,我得到:

C:\sites\YDR\branches\trunk\development\app\static\js\_modules\marketplace\postbacks\Components\Form.js:44
import('Form').then(function (m) {
^^^^^^

SyntaxError: Unexpected token import

at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/ScriptTransformer.js:289:17)
at Object.<anonymous> (__tests__/postbacks-form.js:1:115)

开玩笑的 package.json 部分:

"jest": {
    "rootDir": "./../../",
    "modulePaths": [
      "<rootDir>tools/webpack/node_modules/",
      "<rootDir>development/app/static/css/_modules/",
      "<rootDir>development/app/static/js/_modules/"
    ],
    "transform": {
      "^.+\.js$": "<rootDir>/tools/webpack/jest.transform.js"
    }
  }

jest.transform.js:

// Custom Jest transform implementation that wraps babel-jest and injects our
// babel presets, so we don't have to use .babelrc.
module.exports = require('babel-jest').createTransformer({
    presets: [
        require("babel-preset-react"),
        require("babel-preset-es2015")
    ],
    plugins: [
        require("babel-plugin-syntax-dynamic-import"),
    ]
});

我正在使用以下版本:

我也试过 babel-plugin-dynamic-import-node@1.0.2,但是我有不同的错误:

Plugin 0 specified in "base" provided an invalid property of "default"

已解决。它是 babel-plugin-dynamic-import-node 中的 bug

可以通过添加 .default 来解决:

module.exports = require('babel-jest').createTransformer({
    presets: [
        require("babel-preset-react"),
        require("babel-preset-es2015")
    ],

    plugins: [
        require("babel-plugin-transform-es2015-modules-commonjs"),
        require("babel-plugin-dynamic-import-node").default,
    ]
});

此外,为了能够解析import(),需要babel-plugin-transform-es2015-modules-commonjs。