The use of an import statement outside a module in the /node_modules directory is prohibited

As I embark on migrating some node packages, I find myself facing a significant challenge.

Here is the current state of my package.json file:

{
  //These are the updated dependencies and Jest configurations
  "dependencies": {
    "@google-cloud/logging-winston": "^4.0.2",
    "@google-cloud/secret-manager": "^3.2.3",
    "@google-cloud/storage": "^5.7.0",
    ...
  },
  "devDependencies": {
    "@nestjs/cli": "^8.1.5",
    "@nestjs/schematics": "^8.0.5",
    ...
  },
  "jest": {
    ...
  }
}

Upon attempting to run Jest, I encountered an error related to /node_modules

● Test suite failed to run

    Jest encountered an unexpected token

    ...

    Details:

    /home/{username}/{project_directory}/node_modules/mongodb/src/bson.ts:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import type {
                                                                                      ^^^^^^

    SyntaxError: Cannot use import statement outside a module

      at Runtime.createScriptFromCode (../node_modules/jest-runtime/build/index.js:1728:14)
      at Object.<anonymous> (../node_modules/mongodb/src/bson.ts:8:12)

We were able to resolve this issue within our team by making adjustments to the Jest configuration, specifically changing:

"moduleDirectories": [
  "node_modules",
  "src"
],

To:

"moduleDirectories": [
  "node_modules",
],

In addition, we needed to revert back to relative import paths. This solution successfully eliminated the error, but we're curious as to why it works. Any insights?

Thank you!

Answer №1

Today, I encountered the same issue and was frustrated that mongoose v5 was working smoothly while v6 was throwing me this annoying error. After spending a couple of hours trying to solve it, I finally found a solution that worked for me.

All I had to do was add just one word to my jest.config.js file.

// before
moduleDirectories: ['node_modules', 'src']

// after
moduleDirectories: ['node_modules', '<rootDir>/src']

I believe the problem stemmed from the location of the bson.ts file, which is situated under /node_modules/mongodb/src/bson. Since the path contains src, it might have clashed with the jest configuration where we also specify src. By utilizing <rootDir>, we were able to resolve the issue as it restricts paths that do not originate from the root directory, ensuring smooth testing functionality.

Answer №2

Your setup may be missing the necessary configuration for ES6 import and export functionalities. To enable this feature, you can include the following code snippet in your package.json file:

"type": "module"

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

Tips on maintaining and hiding the vertical scrollbar when a popup is open, alongside the navigation bar positioned at the top of the page

After reviewing this pen, my goal is to create a popup that maintains access to the navigation bar (hence avoiding Bootstrap's Modal). However, I am facing the challenge of keeping the scrollbar visible while preventing scrolling in the background whe ...

Failure of props to synchronize with parent instance information

I'm currently facing an issue with my "Product" component where the data from the parent is not being passed to the child. It seems to be stuck at the default value entered in the main template. The shipping cost should be either free or $2.69 dependi ...

Guide to Retrieving 'req' in JavaScript within Node.js / Express Framework

I have a loaded page named tournament/:key, where a Tournament object is passed. The Jade template accesses variables from the Tournament using syntax like #{tournamentData.name} to display the data on the page. The list of matches is stored as an array wi ...

Learn the trick to make this floating icon descend gracefully and stick around!

I'm trying to create a scrolling effect for icons on my website where they stay fixed after scrolling down a certain number of pixels. I've managed to make the header fixed after scrolling, but I'm unsure how to achieve this specific effect. ...

Guide on implementing register helpers with node.js and express handlebars

When loading a record, I have a select option on my form and want to pre-select the saved option. Here is the code: The Student.hbs file displays the form, with the act obj coming from the student.js route student.hbs <form> <div class="for ...

Is there a way to incorporate a customized npm package into my project?

In my project, I utilize Primus as a wrapper for websockets libraries like sockjs. When the server boots up, Primus generates a script that is then fetched by the client to handle socket connections. However, the problem arises because the embedded source ...

JavaScript: unable to locate information within JSON reply

Looking to develop a Twitter bot utilizing the Twitter and Spotify APIs. Making progress, but encountered an issue I can't tackle alone: Seeking the artist and song name of the top 1 track from the top 50 Spotify songs. Upon sending a request to the ...

Is there a way to assign a value to a select option without relying on jQuery?

I'm working on converting a jQuery code to vanilla JavaScript $('.city option[value="NY"]').attr('selected','selected'); How can I achieve this? The following code is giving me an error document.querySelector('#ci ...

Filtering objects in AngularJS is a complex task, especially when you need to be able to search for a specific value but also consider if that value exists

Struggling to convey my thoughts in English, but here it goes. Imagine two objects linked by colorid: $scope.fruits = {{name:"apple",colorid:"1"},etc}; $scope.colors = {{id:"1",value:"red"}; I've created a table with search and filter function ...

Adding Angular to your current project involves integrating the framework into your

Previously, the task of initializing a project was done using ng init, but that command no longer exists. Another option is to run ng new from a higher level in the directory structure and specify the folder for your existing project. However, this will ...

Steps on fetching information from an asynchronous method in a separate component [Next JS]

Attempting to utilize the newly developed Gemini API, I am employing server actions to extract user messages from input and then sending those messages to the Gemini function for a textual response. "use server"; import runChat from "@/util ...

Is it possible to send a POST request to a PHP file from multiple HTML files using

I am currently working with 3 HTML files for uploading images to specific folders and sub-folders. The issue I encounter is that, while the image successfully moves to the designated folder when submitting from the first two HTML pages, there seems to be a ...

Add a CSS class to a different element when hovering

I have the following HTML structure: <div class="container"> <div class="list-wrapper"> <ul> <li class="item-first"> </li> </ul> </div> <div class="description-wrapper"> <d ...

The error message that popped up was: "Unable to interpret property 'split' of an unspecified value."

I am attempting to run the current npm bin on elastic-beanstalk as a container command, but I keep encountering the following error message: 0 info it worked if it ends with ok 1 verbose cli [ '/usr/bin/node', '/usr/bin/npm', 'bin ...

Invoke the ngrx component store's Effect in a synchronous manner

In the ComponentStore of ngrx, we have two effects. readonly startAndUpdateProgress = this.effect<void>( (trigger$) => trigger$.pipe( exhaustMap(() => this.numbersObservable.pipe( tapResponse({ next: (p ...

When utilizing div.load, jQuery and other JavaScript sources may not be defined

When you load a page using jQuery load: $("#myDiv").load("page.php",{foo: bar}); The head section is included in the index: <head> <script src="/assets/plugins/jQuery/jQuery-2.1.4.min.js"></script> <script src="/assets/plugi ...

Angular data binding between an input element and a span element

What is the best way to connect input texts with the innerHTML of a span in Angular6? Typescript file ... finance_fullname: string; ... Template file <input type="text" id="finance_fullname" [(ngModel)]="finance_fullname"> <span class="fullnam ...

An issue arises during the build process of a React app with the error message appearing as 'ERR_REQUIRE_ESM

Whenever I try to run the build command for my React application, I encounter an error that causes the build to fail: var stripAnsi = require('strip-ansi'); ^ Error [ERR_REQUIRE_ESM]: require() of ES Module C:\Users\ra ...

Encountered a CPU-side conversion issue causes Browser to crash when attempting to load an object using threejs

After implementing the code from the threejs example/loader/obj/mtl to load an object exported via Unity3d, some customers have reported browser crashes on their machines. A screenshot of the error message in a browser console can be viewed here. Addition ...

Converting a JavaScript timestamp into a human-readable date and time using as.POSIXct in R

Is there a way to convert a timestamp from this format into a readable human date? I have generated the timestamp using JavaScript: Date.now(); An example of the output is: 1468833354929 After storing it in a database, when I attempt to convert it usi ...