js require import .ts file instead of .js

3.1k views Asked by At

I have a index.ts and a User.ts file

the index.ts file imports User:

import User from './User'

I then use tsc to transpile the ts files to js files and then I run the index file:

tsc index.ts node index.js

Unfortunately this gives me this error:

(node:1672) UnhandledPromiseRejectionWarning: C:\temp\dev\models\User.ts:1
(function (exports, require, module, __filename, __dirname) { import {Column, Entity, JoinColumn, ManyToOne, OneToMany, PrimaryGeneratedColumn} from "typeorm"
                                                              ^^^^^^

SyntaxError: Unexpected token import

So it seems that my import statement import User from './User' is transpiled to User = require('./User') and still imports the User.ts file instead of the User.js

2

There are 2 answers

2
Joe Clay On

The TypeScript compiler won't automatically compile things that you import - if that's something you want, you're best off using something like Webpack or Parcel. To get all of the files in your project to compile and import properly, you'll have to explicitly ask tsc to do so.

There's two ways you can do this:

  • Pass multiple arguments to tsc - e.g. tsc index.ts User.ts.
  • If you have a .tsconfig file in the directory, you can just run tsc to compile all .ts files. Note that if you have a files list in your .tsconfig, it'll just compile those files.
0
Meshack Mbuvi On

I think the problem is how you have configured you ormconfig.json It should look like this:

{
...
"entities": [
// change "src/entity/*.ts to

"dist/entity/*.js"
],
...
}