簡體   English   中英

Jest 無法使用 Typescript 導入(語法錯誤:無法在模塊外使用導入語句)

[英]Jest fails to import with Typescript (SyntaxError: Cannot use import statement outside a module)

當我使用 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()],
    }

我遇到了同樣的問題,請檢查您的導入中的所有路徑是否正確,在我的情況下,我import NavbarCollapse from "react-bootstrap/esm/NavbarCollapse"; 而不是import NavbarCollapse from "react-bootstrap/NavbarCollapse";

我認為問題出在

  "module": "node",

tsconfig.json 中的一行。 去掉那個。 您的 compilerOptions 部分中有正確的模塊規范(commonjs)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM