0

I'm pretty new to node.js and I'm confused with the import/export system. If I install a package using NPM in my project's node_modules directory, should I eye-check it to know whether it has used the ES6 module system or the CommonJS module system to export its things, and then use the same system for my imports accordingly?!

Node's documentation says it's interoperable in imports:

An import statement can reference an ES module or a CommonJS module.

However, it doesn't seem to work in my case. My problem is, I have set "module": "commonjs", in my tsconfig.json file and so the compiled output will have commonJS imports, however, in a typescript test file I have imported node-fetch like this: import fetch from 'node-fetch', then when I compile it (tsc) and run jest on the files in the build directory it gives this error:

SyntaxError: Cannot use import statement outside a module

16 | const supertest_1 = importDefault(require("supertest"));

---> 17 | const node_fetch_1 = importDefault(require("node-fetch"));

When I search the above error on StackOverflow the existing answers say "jest does not support ES6 modules completely yet (the support is experimental)", however, the point is, I am not using ES6 module imports in this case at all!. As I explained, the compiled files will have commonJS imports... (and jest is running those compiled tests too).

Here are some parts of my code that might be relevant to this question:

// jest.config.js
const { defaults } = require('jest-config');

/** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */
module.exports = {
  testMatch: ["**/dist/test/**/*", ...defaults.testMatch],
};
// test/example-test.ts
import app from '../src/app';
import request from "supertest";
import fetch from 'node-fetch';

describe(" ..... ", () => { //...

Is it a problem of jest? Or a problem of node-fetch? Or even maybe the imports in the compiled output of TypeScipt?

Also here's the compiled import:

// dist/test/example-test.js
//...
const app_1 = __importDefault(require("../src/app"));
const supertest_1 = __importDefault(require("supertest"));
const node_fetch_1 = __importDefault(require("node-fetch"));
aderchox
  • 3,163
  • 2
  • 28
  • 37

1 Answers1

1

Oh wow figured it out, for future visitors...

Don't include a jest.config.js and add a babel.config.js with:

module.exports = {
presets: [['@babel/preset-env']],
};

makes sure to have

"@babel/core": "^7.18.9",
"@babel/preset-env": "^7.18.9",
"babel-jest": "^28.1.3",

in package.json