【问题标题】:import with jest error: Unexpected token import带有开玩笑错误的导入:意外的令牌导入
【发布时间】:2017-06-14 19:19:42
【问题描述】:

我见过类似的问题,但仍然找不到可行的解决方案。

我正在尝试将 Jest 集成到一个工作项目中,该项目在数百个地方使用导入/导出默认值。以下测试确实适用于使用 require 的 Jest:

const bar = require('../../flows/foo');

test('adds 1 + 2 to equal 3', () => {
  expect(bar.foobar(1, 2)).toBe(3);
});

当导出是:

module.exports = { 
 foobar: foobar,
  fizz: fizz
}

我想要测试的函数是通过以下方式导出的:

export default {
  foobar: foobar,
  fizz: fizz
};

所以当我尝试更新我的测试以导入时:

import foobar from '../../flows/foo';

带出口:

export default {foobar: foobar};

我得到了错误

SyntaxError: Unexpected token import

【问题讨论】:

  • 您找到解决方案了吗?

标签: import jestjs


【解决方案1】:

只需要:

// run this command (or npm equivalent)
yarn add @babel/core @babel/preset-env

// add babel.config.js
module.exports = {
  presets: [
    [
      '@babel/preset-env',
      {
        targets: {
          node: 'current'
        }
      }
    ]
  ]
};

Jest 自动拾取,无需其他配置。

【讨论】:

    【解决方案2】:

    您尚未在项目中设置.babelrc 文件,因此不会进行转译。您需要将 ES6+ 语法(importexport 等)转译为浏览器可读的 ES5。

    【讨论】:

      【解决方案3】:

      感谢this GitHub issue post,我遇到了这个问题并以这种方式解决了它:

      如果您使用 babel 转译您的代码,请记住使用 transform-es2015-modules-commonjs 插件。

      要使用它,您需要:

      1. 通过在 CLI 中输入以下命令来安装 BabelJS 插件:

      npm install --save-dev babel-plugin-transform-es2015-modules-commonjs

      1. 将插件添加到 babel 配置中的插件列表中
      plugins: [
        "transform-es2015-modules-commonjs"
      ]
      

      【讨论】:

        猜你喜欢
        • 2017-09-13
        • 1970-01-01
        • 2019-07-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-10
        • 1970-01-01
        • 2018-04-04
        相关资源
        最近更新 更多