Conflict between CommonJS and ES Modules in the project and how handle module formats (Node.js, NEST, Vitest and Typescript)
In this project I’m using Nest with TypeScript and Vitest for the testing environment. I’m using ESM module imports.
The project was running normally without the "type": "module" on the package.json until I install Vitest in the project. The vitest.config.ts file is as follows:
import swc from 'unplugin-swc';
import { defineConfig } from 'vitest/config';
import tsConfigPaths from 'vite-tsconfig-paths'
export default defineConfig({
test: {
globals: true,
root: './',
},
plugins: [
tsConfigPaths(),
swc.vite({
module: { type: 'es6' },
}),
],
});
After running the command npm vitest run, the console started to show the following error:
"module.exports" is not a valid value for the "type" field [package.json]
package.json:3:10:
3 │ "type": "module.exports",
╵ ~~~~~~~~~~~~~~~~
The "type" field must be set to either "commonjs" or "module".
X [ERROR] "vite-tsconfig-paths" resolved to an ESM file. ESM file cannot be loaded by `require`. See https://vitejs.dev/guide/troubleshooting.html#this-package-is-esm-only for more details. [plugin externalize-deps]
The plugin "externalize-deps" was triggered by this import
vitest.config.ts:3:26:
3 │ import tsConfigPaths from 'vite-tsconfig-paths'
╵ ~~~~~~~~~~~~~~~~~~~~~
Following the troubleshooting recommendations, I added "type": "module" to my package.json, and that solved the problem. However, when I ran the server again with npm nest start, the console started showing the following error:
file: ..../dist/src/main.js:2
Object.defineProperty(exports, "__esModule", { value: true });
^
ReferenceError: exports is not defined in ES module scope
This file is being treated as an ES module because it has a '.js' file extension and 'D:\...\package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
So, to run the server, I have to remove "type": "module"from my package.json, but to run the Vitest environment tests, this line needs to be added. I’ve searched for a solution but couldn’t find one. Can anyone help me?
Read more here: Source link
