-2

I'm creating a node (express app) and I'm having some errors when I try to import one module.

I have a seeder.ts file where I want to connect to the database.ts and populate the db.

But I'd had problems with TS modules. I've had the issue where TS needs to know whether a file should be treated as a module or a script.

'Cannot redeclare block-scoped variable' -> The solution was to add export {} to all files, included the database.ts (as you could read here: 'Cannot redeclare block-scoped variable' in unrelated files )

So then, when I run the script to populate the db: node ./seeder.ts, where I do const db = require("./database.ts"): I got this other error:

'SyntaxError: Unexpected token 'export'' -> The solution would be to remove the export {} from all files (check this Getting Unexpected Token Export )... Then I'll have the first error again :(

Is there any other alternative here?

fitu
  • 119
  • 2
  • 12
  • 3
    You're trying to execute a TypeScript file with node.js, which can't work - you need to transpile it first to strip off the type annotations. Also why are you using `require` when you want to use ES6 modules? Do `import` instead. – Bergi Dec 13 '21 at 01:25

1 Answers1

1

You need to understand the difference between modules (es6 import/export) and commonjs (require/module.exports). You can decide which way you want to choose. The quick fix is in adding in your package.json

"type" : "module"

And don't forget to change the require to the new es6 import.