Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: Unexpected token import

Just started working with typescript. Unfortunately when I try to build for production it fails.

Firstly I run

tsc

This passes without any error, but when I try to run the build file I get import errors

node build/index.js

The error I get is below:

[0] (function (exports, require, module, __filename, __dirname) { import {
[0]                                                               ^^^^^^
[0]
[0] SyntaxError: Unexpected token import
[0]     at createScript (vm.js:80:10)
[0]     at Object.runInThisContext (vm.js:139:10)

Below is my tsconfig

{
    "include": [
        "src/**/*"
    ],
    "exclude": [
        "node_modules",
        "**/*.spec.ts"
    ],
   "compilerOptions": {
        "lib": [
            "es5",
            "es6",
        ],
        "pretty": true,
        "target": "es5",
        "module": "commonjs",
        "outDir": "./build",
        "moduleResolution": "node",
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "allowSyntheticDefaultImports": true,
        "sourceMap": true
   }
}

I am using node v8.9.3

like image 938
James Okpe George Avatar asked Mar 10 '18 13:03

James Okpe George


2 Answers

If you use TypeORM there can be a problem with your ormconfig. Your configuration file probably contains path like src/entities/*.ts in the entity section. So it causes requiring *.ts files from your src folder, not from dist folder.

like image 62
bogomya Avatar answered Sep 28 '22 06:09

bogomya


When working with NodeJs, your tsconfig.json should look like this:

{
    "include": [
        "src/**/*"
    ],
    "exclude": [
        "node_modules",
        "**/*.spec.ts"
    ],
   "compilerOptions": {
        "lib": ["es6"],        // No need for "es5" if you have "es6"
        "types": ["node"],      // When you code for nodejs
        "target": "es6",       // NodeJs v8.9.3 supports most of the es6 features
        "pretty": true,
        "module": "commonjs",
        "outDir": "./build",
        "moduleResolution": "node",
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "allowSyntheticDefaultImports": true,
        "sourceMap": true
   }
}
like image 23
gilamran Avatar answered Sep 28 '22 07:09

gilamran