Trouble arises when trying to import Jest with Typescript due to SyntaxError: Import statement cannot be used outside a module

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

Answer №1

Encountered a similar issue, it's important to verify that all import paths are accurate. In my situation, I mistakenly used

import NavbarCollapse from "react-bootstrap/esm/NavbarCollapse";
instead of the correct
import NavbarCollapse from "react-bootstrap/NavbarCollapse";

Answer №2

It appears that the issue lies within

  "dependency": "node_modules",

entry in your package.json file. You should consider removing this line as the correct dependency specification (commonjs) can be found within your project's configuration.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Obtaining the accurate return type based on the generic parameter in a generic function

Is there a way to determine the correct return type of a function that depends on a generic argument? function f1<T>(o: T) { return { a: o } } // How can we set T to number through (n: number)? type T1 = typeof f1 extends (n: number) => infe ...

Unable to connect to server using local IP address

Currently utilizing a freezer application () and encountering an issue where I can only access the server on localhost. I attempted to modify the settings.js file by replacing 127.0.0.1 with 0.0.0.0, rebuilt it, but it still persists on localhost. Even aft ...

Removing a dynamic TypeScript object key was successful

In TypeScript, there is a straightforward method to clone an object: const duplicate = {...original} You can also clone and update properties like this: const updatedDuplicate = {...original, property: 'value'} For instance, consider the foll ...

Guide to integrating Webpack 3.8.1 into a Vue application

So I have this scaffold: https://github.com/vuejs/vue-cli Now, my goal is to integrate Webpack 3.8.1 into it. There's an existing "build" folder with numerous webpack files in it : https://i.stack.imgur.com/MJ3JP.png However, when I try running "w ...

Encountering a RuntimeError during the integration of Angular Js in Rails with ExecJS

Currently, I'm working on integrating Angular Js into a Rails Project and I've been following the tutorial provided at . However, after completing all the steps, I encountered the following error: https://i.sstatic.net/ehYCb.png I've searc ...

Syntax of the Vue.js application object model

Just delving into the world of vue.js and stumbled upon this code snippet. Curious to know more about its structure. const CounterApp = { data() { return { counter: 0 } }, mounted() { setInterval(() => { this.counter++ ...

Sharing data between ejs and javascript files

When using Express, I have encountered an issue with passing a variable to an EJS file called "index.ejs". res.render("index",{passedUser:req.user.alias}) Although I am able to successfully print it using <%=passedUser%> in the EJS file, I require ...

Utilizing the adapter design pattern in Angular with TypeScript for enhancing a reactive form implementation

I've been struggling to understand how to implement the adapter pattern in Angular6. Despite reading numerous articles and tutorials, I still can't quite grasp the concept. Could someone provide some insights on this topic? Essentially, I have a ...

Angular RxJS: The never-ending reduction

I have developed a component that contains two buttons (searchButton, lazyButton). The ngOnDestroy method is defined as follows: public ngOnDestroy() { this.unsubscribe$.next(); this.unsubscribe$.complete(); } I have created two observables from ...

The Date object in Typescript is represented as a string

My typescript interface includes a variable called start, which is typed as Date | null. This data is retrieved from a dotnet API that returns a DateTime object. The issue arises when the start variable is passed through a function in Date-fns, causing a R ...

Maximizing the potential of PJAX with Express and EJS: A guide

Hey there, question coming from a newbie in the world of coding. I've been struggling to make pjax work for quite some time now without any success. The closest I've come is seeing some activity in the terminal, but when I click on the link, it ...

The AutoComplete feature in Formik Field from Material UI component is not showing the InitialValues

Having an issue with displaying the initialValues in the AutoComplete component from the Material UI library when used in a Formik Field. Even though values are passed as initial, they do not render in the component, although if the form is submitted, they ...

Toggle the JavaScript on/off switch

I am attempting to create a toggle switch using Javascript, but I am encountering an issue. Regardless of the class change, the click event always triggers on my initial class. Even though my HTML seems to be updating correctly in Firebug, I consistently ...

Dealing with client-side exceptions in a Next.js 13 application's directory error handling

After carefully following the provided instructions on error handling in the Routing: Error Handling documentation, I have successfully implemented both error.tsx and global-error.tsx components in nested routes as well as the root app directory. However, ...

Divide the table row and store each cell using regular expressions

Here is the original source text: gi0/1 1G-Fiber -- -- -- -- Down -- -- Access gi0/2 1G-Fiber -- -- -- -- Down -- -- gi0/3 1G-Fiber -- -- -- -- Down -- -- gi0/4 1G-Fiber -- -- -- -- Down -- -- gi0/5 1G-Fiber -- -- -- -- Down -- -- gi0/0/1 1G-Fiber -- ...

The error message "external.js: $ is not defined" indicates that

Recently, I integrated an external JavaScript file into my Angular 14 project. This JS file contains the event $('.class').click(). However, every time I launch the application on localhost, a message pops up in the browser stating that $ is not ...

The outcome of AES encryption varies when comparing Node JS with C# programming languages

In a particular scenario, I need to encrypt and transmit text using the AES 256 algorithm. The decryption process will be handled by client-side C# code. Here is the encryption code in JavaScript: const crypto = require('crypto'); algorithm = ...

Execute command problem

Explaining this code may be a bit tricky, but I'll do my best. Below is the code snippet for executing a slash command. client.on('interactionCreate', async interaction => { if (!interaction.isCommand()) return; const command = c ...

The navigation bar is positioned with white space above it

Currently working on a website design and facing an issue with adding a clickable button to the Nav-bar. Noticed some white-space above the Nav-bar which is not desired. I had previously posted a similar question but unable to identify the CSS error causi ...

Difficulty encountered while managing dropdown functionality in Protractor using TypeScript

I'm encountering some difficulties when it comes to selecting a dropdown in Protractor. Here's the structure of my DOM: https://i.stack.imgur.com/qK8sT.png This is the XPath I'm using to select the dropdown with the value "Yes": //label[ ...