【问题标题】:Jest fails to import with Typescript (SyntaxError: Cannot use import statement outside a module)Jest 无法使用 Typescript 导入(语法错误:无法在模块外使用导入语句)
【发布时间】:2021-01-05 13:08:00
【问题描述】:

当我使用 Typescript 运行 Jest 测试时,在 node_modules 库中调用的外部 TS 文件导入时出现以下错误:

SyntaxError: Cannot use import statement outside a module

我确定我缺少配置,但它是什么?感谢您的帮助。

这是我的配置:

  • tsconfig.json
{
  "compilerOptions": {
    "sourceMap": true,
    "module": "commonjs",
    "moduleResolution": "node",
    "esModuleInterop": true,
    "allowJs": true,
    "jsx": "react",
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "baseUrl": "./",
    "paths": {
      "*": ["src/*"]
    }
  },
  "strict": true,
  "module": "node",
  "compileOnSave": false,
  "include": ["src", "tests"]
}
  • jest.config.js

    module.exports = {
      roots: ['<rootDir>'],
      preset: 'ts-jest',
      testRegex: 'tests/.*\\.test.(js|jsx|ts|tsx)$',
      transform: {
        '^.+\\.tsx?$': 'ts-jest',
      },
      moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
      moduleDirectories: ['node_modules', 'src'],
      setupFilesAfterEnv: ['<rootDir>/tests/jest.setup.ts'],
      collectCoverage: true,
      collectCoverageFrom: ['src/**/*.{js{,x},ts{,x}}', '!src/index.tsx'],
    }

  • webpack.config.js

    /* eslint-disable @typescript-eslint/no-var-requires */
    const path = require('path')
    const webpack = require('webpack')
    
    module.exports = {
      entry: './src/index.tsx',
      mode: 'development',
      module: {
        rules: [
          {
            test: /\.jsx?$/,
            exclude: /node_modules/,
            loader: 'babel-loader',
            options: { presets: ['@babel/env'] },
          },
          {
            test: /\.tsx?$/,
            exclude: /node_modules/,
            loader: 'ts-loader',
          },
          {
            test: /\.css$/,
            exclude: /node_modules/,
            use: ['style-loader', 'css-loader'],
          },
        ],
      },
      resolve: {
        extensions: ['.js', '.jsx', '.ts', '.tsx'],
        alias: { 'react-dom': '@hot-loader/react-dom' },
      },
      output: {
        path: path.resolve(__dirname, 'dist/'),
        publicPath: '/dist/',
        filename: 'app.js',
      },
      devServer: {
        contentBase: path.join(__dirname, 'public/'),
        port: 3000,
        publicPath: 'http://localhost:3000/dist/',
        hotOnly: true,
      },
      plugins: [new webpack.HotModuleReplacementPlugin()],
    }

【问题讨论】:

  • 这看起来像是 12 的副本。我能够通过添加 transform-es2015-modules-commonjs 来解决这个问题。有关详细信息,请参阅此帖子:stackoverflow.com/a/63962423/2684661

标签: javascript typescript webpack jestjs babeljs


【解决方案1】:

我认为问题出在

  "module": "node",

tsconfig.json 中的行。删除它。您的 compilerOptions 部分中有正确的模块规范(commonjs)。

【讨论】:

  • 谢谢蒂姆。我删除了该行,但在运行测试时仍然存在问题。我想当前的配置很好,因为我可以毫无问题地运行应用程序,但一定有一些特定于 Jest 的东西丢失了......
  • 您的项目是否有 .js 文件和 .ts 文件?如果是这样,您可以尝试:preset: 'ts-jest/presets/js-with-ts',
  • 我没有。我仍然尝试以防万一,但仍然无法正常工作。该问题似乎只发生在node_modules 中的库导入的.ts 文件中。即使我在transformIgnorePatterns 中将其作为例外添加(甚至与! 相反),它也不会改变任何东西。
  • 您能否提供更多有关导致语法错误的行的信息?它是在测试文件中,还是在正在测试的文件中?文件中是否还有其他有效的导入语句?
  • 在源文件中,我使用的是Web3 库。失败的行是node_modules/ethereum-cryptography/src/secp256k1.ts:1,包含:import { privateKeyVerify } from "secp256k1";
【解决方案2】:

我遇到了同样的问题,请检查您的导入中的所有路径是否正确 就我而言,我有import NavbarCollapse from "react-bootstrap/esm/NavbarCollapse"; 而不是import NavbarCollapse from "react-bootstrap/NavbarCollapse";

【讨论】:

  • 问题发生在node_modules 的库中,没有错误的导入。而且我的应用运行良好,只是测试不起作用。
猜你喜欢
  • 2021-07-02
  • 2022-11-17
  • 1970-01-01
  • 2021-10-06
  • 1970-01-01
  • 2021-12-03
  • 2023-01-04
  • 1970-01-01
  • 2021-10-18
相关资源
最近更新 更多