2

When I run Jest tests with Typescript, I get the following error on an external TS file import called in a node_modules library:

SyntaxError: Cannot use import statement outside a module

I'm sure I'm missing a configuration but what is it? Thanks for your help.

Here is my configuration:

  • 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()],
    }

1
  • This looks like a duplicate of 1 and 2. I was able to fix this issue by adding transform-es2015-modules-commonjs. See this post for more details: stackoverflow.com/a/63962423/2684661 Commented Sep 18, 2020 at 21:26

2 Answers 2

4

I had the same problem, please check if all paths in your imports are correct in my case i had import NavbarCollapse from "react-bootstrap/esm/NavbarCollapse"; instead of import NavbarCollapse from "react-bootstrap/NavbarCollapse";

Sign up to request clarification or add additional context in comments.

2 Comments

The issue is happening inside a library in node_modules, there is no wrong import with it. And my app runs fine, it's just the test that doesn't work.
+1 this, this is an issue with VSCode sometimes importing from wrong node_modules dir with it's auto import feature. Didn't notice the 'esm' bit for hours!
0

I think the problem is with the

  "module": "node",

line in your tsconfig.json. Remove that. You have the correct module specification (commonjs) inside your compilerOptions section.

6 Comments

Thank you Tim. I removed the line but I still have the issue when running the test. I guess that the current config is fine since I can run the app without any issue, but there must be something specific to Jest that is missing...
Does your project have .js files as well as .ts? If so, you could try: preset: 'ts-jest/presets/js-with-ts',
I don't. I still tried it just in case but still doesn't work. The issue seems to happen only for a .ts file imported by a library in node_modules. Even if I add it as an exception in transformIgnorePatterns (even the opposite with !), it doesn't change anything.
Can you provide some more information about the line that is causing the syntax error? Is it in a test file, or in a file that is being tested? Are there other import statements in the file that work?
In a source file, I'm using the Web3 library. The line failing is node_modules/ethereum-cryptography/src/secp256k1.ts:1 containing: import { privateKeyVerify } from "secp256k1";
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.