The error message "SyntaxError: Cannot use import statement outside a module" is encountered when trying to import node-fetch in a Typescript file

I'm facing some challenges with the development of a typescript library npm package. The problem arises when I attempt to import node-fetch for fetch calls. To illustrate my issue, I have set up a sample git repository.

These are the commands I used to reach this stage:

npm i --save-dev typescript ts-node jest @types/jest ts-jest
jest --init
npm i node-fetch

In my package.json, I configured it as follows:

"main": "dist/index.js",
"types": "dist/index.d.ts",
"files": [
  "/dist"
],
"scripts": {
  "test": "jest --coverage",
},

In my tsconfig.json, here is the configuration:

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es2015",
    "declaration": true,
    "outDir": "./dist"
  },
  "include": ["src/**/*"]
}

The content of my jest.config.js is:

module.exports = {
  preset: "ts-jest",
  testEnvironment: "node",
  transformIgnorePatterns: ["/node_modules/"],
};

Upon running npm text, I receive the following result:

> <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0d797e61646f4d3d233c233d">[email protected]</a> test
> jest --coverage

 FAIL  tests/unit/index.test.ts
  ● Test suite failed to run

    Jest encountered an unexpected token
    
    [Additional details about Jest error]

    Does anyone have any suggestions? How can I successfully integrate node-fetch into my Typescript project?</p>
<p>Edit 1: By installing <a href="https://github.com/sindresorhus/got" rel="nofollow noreferrer">Got</a> using the command <code>npm i got, I encounter the same error.

Edit 2: Included the content of the jest.config.js file

Answer №1

Are you utilizing a Jest configuration file? It is essential to specify the use of ts-jest, as mentioned in the third line of jest documentation. Without a babel config file present, Jest may struggle to interpret non-JavaScript syntax such as TypeScript, resulting in SyntaxError.

To resolve this issue, consider executing the following command: npx ts-jest config:init Alternatively, if you prefer using Yarn, try: yarn ts-jest config:init

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

What is the best way to implement multiple ternary operators within HTML code?

Consider the following code snippet: It currently applies CSS classes up to red4, but I want to apply CSS classes up to red11. Additionally, the variable "size" in myData should be dynamic. For example, size could range from 0-20 // 0-100 // 0-10000, etc., ...

What is the best way to set wrapper props without hiding it from showing up in attrs?

Creating a Wrapper Component with Specific Props <script setup lang="ts"> import InputBase,{ Props as InputBaseProps } from "./InputBase.vue"; interface Props extends InputBaseProps { label?: string; labelClassName?: string; ...

Retrieving rows from a MySQL table that contain a specified BIGINT from an array parameter

I've encountered a problem with mysql while using serverless-mysql in TypeScript. It seems like my query might be incorrect. Here is how I am constructing the query: export default async function ExcuteQuery(query: any, values: any) { try { ...

Separating React props based on multiple Typescript interfaces

Is there a way to split the props object in React based on an Typescript interface that extends multiple other interfaces? Alternatively, I could duplicate the props and pass them to components that don't need them, but that would not be the most effi ...

When attempting to publish an index.d.ts file using npm, the module is

We are currently in the process of developing an npm package that will serve as the foundation for most of our projects. However, we have encountered some issues that need to be addressed: The index.d.ts file of our base npm package is structured as shown ...

Troubleshooting why the Typescript Omit property is not functioning correctly when used with the 'as' keyword

When both properties are needed during registration, but only one is necessary after, the system utilizes Firebase built-in functions for authentication and registration purposes. All other information will be stored in the Firebase user collection. The i ...

Typescript in Firebase Functions organization

Struggling with typescript organization in my firebase functions. I'm fine keeping trigger functions in index.ts for now, but need help organizing other utility functions elsewhere. Current index.ts setup: import * as functions from 'firebase-f ...

Utilizing shared components across a Next.js application within a monorepo

Utilizing a monorepo to share types, DTOs, and other isomorphic app components from backend services (Nest.js) within the same mono repo has presented some challenges for me. In my setup, both the next.js app and nest.js app (which itself is a nest.js mono ...

Configuring environment variables during Jest execution

A variable is defined in my `main.ts` file like this: const mockMode = process.env.MOCK_MODE; When I create a test and set the variable to true, it doesn't reflect as `'true'` in the main file, but as `'false'` instead. describe ...

Create an interface that adheres to the defined mapped type

Working on a typescript project, I have defined the mapped type GlanceOsComparatorV2 interface DonutData { label: string; value: number; } interface ProjectMetric { value: number; } enum ZoneMetricId { ClickRate = 'clickRate', } enum Pa ...

Exploring Mixed Type Arrays Initialization in Typescript using Class-Transformer Library

In my class, I have a property member that is of type array. Each item in the array can be of various types such as MetaViewDatalinked or MetaViewContainer, as shown below class MetaViewContainer{ children: (MetaViewDatalinked | MetaViewContainer)[]; ...

Streamline your Javascript code by utilizing multiple logical operators within a filter function

Looking for some help simplifying this code. Can anyone assist? I need to make changes to this code because I made an error. Correction needed: Updated test filter function: this._test = test?.filter(({ foo }: Foo) => { return foo ...

Hide Angular Material menu when interacting with custom backdrop

One issue I am facing is with the menu on my website that creates a backdrop covering the entire site. While the menu can be closed by clicking anywhere outside of it, this functionality works well. The problem arises when users access the site on mobile ...

Jest is simulating a third-party library, yet it is persistently attempting to reach

Here's a function I have: export type SendMessageParameters = { chatInstance?: ChatSession, // ... other parameters ... }; const sendMessageFunction = async ({ chatInstance, // ... other parameters ... }: SendMessageParameters): Promise<vo ...

Oh no! A critical mistake has occurred: Mark-compact operations are not working efficiently near the heap limit, leading to a failed allocation due to the

My project is not particularly complex, I only just started it. However, when I run the command npm run dev, node js consumes more than 4GB of memory and eventually crashes with a fatal error: --- Last few GCs --- [16804:0000018EB02350F0] 128835 ms: Mar ...

Replacing URLs in Typescript using Ionic 3 and Angular

Currently facing some difficulties getting this simple task to work... Here is the URL format I am dealing with: https://website.com/image{width}x{height}.jpg My objective is to replace the {width} and {height} placeholders. I attempted using this func ...

Show details on map click with Angular's OpenLayers integration

When working with an Angular2 component, I am trying to retrieve the element id on a click event on an OpenLayers map within the ngOnInit function. Below is the code I am using: map.on("click", (e) => { map.forEachFeatureAtPixel(e.pixel, function ( ...

How can I import HTML code containing JS from an external source in just one line of code?

I am looking to add external functionality to my web page using a single line .js import that works similar to a plugin. Here is what I currently have: <!--index.html--> <head> </head> <body> <!-- Here is the one-line scrip ...

Is it possible to retrieve the distinct errors detected by ESLint?

I'm currently in the process of refactoring a project using TypeScript and React. After adding ESLint, I found over 300 errors scattered throughout the codebase. Facing such a significant number of errors, it's clear that these can't all be ...

A step-by-step guide to activating multi-selection in the Primary SideBar of Visual Studio Code using your custom extension

Currently, I'm in the process of developing an extension for Visual Studio Code where I've added a new activityBar containing treeViews that showcase information pulled from a JSON file. My goal is to enable users to multi-select certain displaye ...