【问题标题】:Dynamic imports in Jest produce: SyntaxError: Unexpected token importJest 中的动态导入产生:SyntaxError: Unexpected token import
【发布时间】:2017-05-02 18:11:58
【问题描述】:

还不知道如何解决这些错误,Jest 抱怨动态导入如下:

const importModules = Promise.all([
      import('containers/HomePage/reducer'),
      import('containers/HomePage/sagas'),
      import('containers/HomePage'),
    ]);

错误信息:

F:\react-boilerplate\app\store.js:49
      import('./reducers').then(function (reducerModule) {
      ^^^^^^
SyntaxError: Unexpected token import

您可以在此处找到所有详细信息:https://github.com/mxstbr/react-boilerplate/pull/1358

【问题讨论】:

  • 你的.babelrc 是什么样子的?
  • 您是否尝试过使用相同的插件进行生产和测试。好像 babel 不能用你的 babel env.test 设置编译东西
  • 感谢@AndreasKöberle 的建议,我在测试环境的插件列表中添加了babel-plugin-dynamic-import-node 插件,并且大部分错误都已解决。我猜动态import()s 不能被填充所以节点的唯一选择是将它们转换为requirePromise 内。

标签: javascript reactjs babeljs jestjs


【解决方案1】:

安装babel-plugin-dynamic-import-node 解决了我们的问题。另外,确保babylonbabel 依赖)至少是6.12.0

此外,我们在 Travis 构建时遇到了问题,因为 Travis 缓存了 node_modules 和旧的 babylon

$ npm ls babylon
react-boilerplate@3.3.0 /home/travis/build/mxstbr/react-boilerplate
├─┬ babel-core@6.21.0
│ └── babylon@6.11.1
├─┬ babel-eslint@7.1.1
│ └── babylon@6.14.1 
├─┬ jest-cli@18.0.0
│ └─┬ istanbul-lib-instrument@1.3.0
│   └── babylon@6.14.1 

,所以我们不得不关闭缓存:cache: false

【讨论】:

  • 我有一个类似的问题,即 Jest 测试在本地运行良好(使用 @babel/plugin-syntax-dynamic-import 插件)但在 CI 期间它们会失败。添加 babel-plugin-dynamic-import-node 有效(因为 CI 在节点上运行)。见github.com/facebook/jest/issues/5920#issuecomment-444112504
【解决方案2】:

看起来 jest 无法在您的 .babelrc 文件中使用 test 的 babel 设置编译您的文件。您需要对prodtest 进行相同的设置

【讨论】:

    猜你喜欢
    • 2017-09-16
    • 2018-09-11
    • 2019-11-10
    • 2017-12-30
    • 2017-06-10
    • 2019-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多