How to resolve SyntaxError: Cannot use import statement outside a module when running Vitest and TypeORM #3290
Replies: 3 comments 10 replies
-
I have already tried solutions from these discussions:
And I ended up installing the following dependency: https://github.com/egoist/unplugin-swc, But didn't work for me. |
Beta Was this translation helpful? Give feedback.
-
Your tsc script generates ESM files and your Node.js script runs them with your package.json. If you don't specify that type of your project is |
Beta Was this translation helpful? Give feedback.
-
Did you ever resolve this? I'm trying to set up TypeORM in a project that's been using vitest and am running into this issue. It seems to happen when I initialize the data source with Versionstypeorm@npm:0.3.19 Code// data-source.ts
export const AppDataSource = new DataSource({
type: 'postgres',
poolSize: 5,
url: config.databaseUrl,
logging: !config.isProduction,
entities: [MyEntity],
migrations: ['db/migrations/*.ts'], // Tests run when I comment out this line
migrationsRun: false,
subscribers: [],
}); import { it, describe, expect, beforeAll } from 'vitest';
import { AppDataSource } from '~db/data-source';
beforeAll(async () => {
await AppDataSource.initialize()
.then(() => {
console.log('Data Source has been initialized!');
})
.catch((err) => {
console.error('Error during Data Source initialization', err);
throw err;
});
}); tsconfig.json {
"compilerOptions": {
"allowJs": true,
"allowSyntheticDefaultImports": true,
"alwaysStrict": true,
"baseUrl": "./",
"checkJs": false,
"composite": true,
"declaration": true,
"declarationMap": true,
"emitDecoratorMetadata": true,
"esModuleInterop": true,
"experimentalDecorators": true,
"forceConsistentCasingInFileNames": true,
"incremental": true,
"inlineSourceMap": true,
"module": "nodenext",
"moduleResolution": "nodenext",
"noFallthroughCasesInSwitch": true,
"noImplicitAny": true,
"noImplicitReturns": false,
"outDir": "./build",
"preserveSymlinks": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"strict": true,
"target": "es2020",
"tsBuildInfoFile": "./.tsbuildinfo",
"useUnknownInCatchVariables": false,
"paths": {
"~app/*": ["./app/*"],
"~config": ["./config"],
"~config/*": ["./config/*"],
"~db/*": ["./db/*"],
"~integrations/*": ["./integrations/*"],
"~shared/*": ["./shared/*"]
}
},
"include": [
"./**/*.ts",
"vitest.config.mts",
".eslintrc.js"
],
"exclude": ["build", "dist", "node_modules"]
} // vitest.config.mts
const config = defineConfig({
esbuild: {
format: 'esm',
target: 'es2020',
},
test: {
testTimeout: 20000,
exclude: ['build', 'node_modules'],
globalSetup: [path.resolve(__dirname, './vitest.setup.ts')],
},
resolve: {
alias: {
'~app': path.resolve(__dirname, './app'),
'~config': path.resolve(__dirname, './config'),
'~db': path.resolve(__dirname, './db'),
'~integrations': path.resolve(__dirname, './integrations'),
'~shared': path.resolve(__dirname, './shared'),
'~__recordings__': path.resolve(__dirname, './__recordings__'),
},
},
}); My single migration file so far import { MigrationInterface, QueryRunner, Table, TableUnique } from 'typeorm';
export class AddCachedQueries1705597538034 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.createTable(
new Table({
// ... |
Beta Was this translation helpful? Give feedback.
-
I found the following error while running Vitest tests that require a database connection:
"SyntaxError: Cannot use import statement outside a module."
This issue appeared after I made some changes to my setup. Here's my new script for typeorm:
"migration:generate": "ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli -d ./src/infra/db/postgres/helpers/data-source.helper.ts migration:generate"
The migration file generated by this script is a TS file named "1683049252085-CreateUsersTable.ts." When I changed the file extension from ".ts" to ".mjs", Vitest started running correctly.
Beta Was this translation helpful? Give feedback.
All reactions