Dean Friedland
Dean Friedland

Reputation: 803

Why is my file throwing an error on execution?

I am getting an error when I try to execute a file using the command node database.ts Can anyone tell me what the issue is with my syntax?

The file looks like:

import { Sequelize } from 'sequelize-typescript';

export const sequelize = new Sequelize({
    database : "zemit",
    dialect : "postgres",
    username : "postgres",
    password : "postgres",
    host : "localhost",
    port : 5432
});
sequelize.authenticate().then(() => {
 console.log("Connected to DB");
})
.catch((err) => {
 console.log(err);
})

The error says:

import { Sequelize } from 'sequelize-typescript';
^^^^^^

SyntaxError: Cannot use import statement outside a module
?[90m    at Module._compile (internal/modules/cjs/loader.js:892:18)?[39m
?[90m    at Object.Module._extensions..js (internal/modules/cjs/loader.js:973:10)?[39m
?[90m    at Module.load (internal/modules/cjs/loader.js:812:32)?[39m
?[90m    at Function.Module._load (internal/modules/cjs/loader.js:724:14)?[39m
?[90m    at Function.Module.runMain (internal/modules/cjs/loader.js:1025:10)?[39m
?[90m    at internal/main/run_main_module.js:17:11?[39m

Upvotes: 0

Views: 233

Answers (2)

hoangdv
hoangdv

Reputation: 16147

node runtime system does not support run a Typescript file file as a .js file. If you are working with Typescript, you have to transpile your .ts files to .js file with command tsc (require Typescript installed), then you run your generated .js file with node database.js command (instead of node database.ts)

Or you can use ts-node - TypeScript execution and REPL for node.js, then you can "run" a .ts file directly, with ts-node database.ts command.

Upvotes: 1

Prabhjot Singh Kainth
Prabhjot Singh Kainth

Reputation: 1861

Just replaced all the "imports" with "requires".

I had similar issue, searched online but didn`t got any solution.

Then I replaced import with require and it worked.

Upvotes: 1

Related Questions