Whenever I execute Jest tests using Typescript, I encounter a SyntaxError while importing an external TS file from a node_modules
library:
SyntaxError: Cannot use import statement outside a module
I'm positive that there is a configuration missing, but what could it be? Thank you for your assistance.
Below is the setup I am currently using:
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()],
}