0

I have implemented simple rest api with nodejs and connection to database via typeorm. Here are some snippets of code which I wrote:

import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  Unique,
  CreateDateColumn,
  UpdateDateColumn
} from "typeorm";
import { Length, IsNotEmpty } from "class-validator";
import bcrypt from "bcryptjs";

@Entity()
@Unique(["username"])
export class User {
  @PrimaryGeneratedColumn()
  public id: number;

  @Column()
  @Length(4, 20)
  username: string;
}

tsconfig.json

{
    "compilerOptions": {
        "experimentalDecorators": true,
        "module": "commonjs",
        "esModuleInterop": true,
        "target": "es6",
        "moduleResolution": "node",
        "sourceMap": true,
        "outDir": "dist",
        "emitDecoratorMetadata": true
    },
    "lib": [
        "es2015"
    ]
}

package.json

{
    "name": "node-with-ts",
    "version": "1.0.0",
    "description": "",
    "main": "dist/app.js",
    "scripts": {
        "start": "tsc && node dist/app.js",
        "test": "echo \"Error: no test specified\" && exit 1",
        "tsc": "tsc",
        "prod": "node ./dist/app.js",
        "build": "npm install && tsc -p .",
        "reset": "rm -rf node_modules/ && rm -rf dist/ && npm run build",
        "migration:run": "ts-node ./node_modules/typeorm/cli.js migration:run"
    },
    "author": "",
    "license": "ISC",
    "devDependencies": {
        "@types/express": "^4.16.1",
        "@types/node": "^12.7.5",
        "nodemon": "^1.19.2",
        "ts-node": "8.4.1",
        "tslint": "^5.12.1",
        "typescript": "^3.3.3"
    },
    "dependencies": {
        "@types/bcryptjs": "^2.4.2",
        "@types/body-parser": "^1.17.0",
        "@types/cors": "^2.8.4",
        "@types/helmet": "0.0.42",
        "@types/jsonwebtoken": "^8.3.0",
        "bcryptjs": "^2.4.3",
        "body-parser": "^1.18.1",
        "class-validator": "^0.9.1",
        "cors": "^2.8.5",
        "express": "4.17.1",
        "helmet": "^3.21.1",
        "jsonwebtoken": "^8.4.0",
        "reflect-metadata": "^0.1.13",
        "sqlite3": "^4.1.0",
        "ts-node-dev": "^1.0.0-pre.32",
        "typeorm": "^0.2.12"
    }
}

I have pasted lots of code because I have no idea what is wrong. I am tryinf to run app via npm run start and it throws below error:

> tsc && node dist/app.js

    /Users/workspace/node_typescript_project/src/entity/User.ts:1
    (function (exports, require, module, __filename, __dirname) { import {
                                                                  ^^^^^^

    SyntaxError: Unexpected token import

Although I able to build to project and it generates js codes but when it comes to run application it throws errors.

3
  • Can you give us your node version ? In a terminal node -v. Your issue is that import is a ES6 keyword, and your node version seems to not handle this. Commented Sep 28, 2019 at 19:26
  • node: v8.9.4 npm: 6.11.3 Commented Sep 28, 2019 at 19:38
  • Can you show your project folder structure? Commented Oct 1, 2019 at 1:43

4 Answers 4

3

Your entities are probably not being referenced correctly in your Typeorm config file.

Try to see if you can get it to work with the following ormconfig.js file (pay special attention to the entities property:

// ormconfig.js at root of project
const isDevelopment = process.env.NODE_ENV === 'development';
module.exports = {
  type: 'mysql',
  host: process.env.MYSQL_HOST,
  port: process.env.MYSQL_TCP_PORT,
  username: process.env.MYSQL_USER,
  password: process.env.MYSQL_PASSWORD,
  database: process.env.MYSQL_DATABASE,
  synchronize: isDevelopment,
  logging: isDevelopment,
  entities: [
    isDevelopment ? `src/**/*.entity.ts` : `dist/**/*.entity.js`,
  ],
  migrations: [`src/migration/**/*.ts`],
  subscribers: ['src/subscriber/**/*.ts'],
  cli: {
    entitiesDir: 'src/entity',
    migrationsDir: 'src/migration',
    subscribersDir: 'src/subscriber',
  },
};

With this setup, I have ts-node working directly with my Typescript source files, and only in production do I use tsc to build. When building for prod, I need to reference the .js files inside of the dist folder.

Sign up to request clarification or add additional context in comments.

Comments

0

I am trying to replicate the issue but couldn't replicate it. Just created a sample repo for above code.

https://github.com/pktippa/stackoverflow-questions/tree/master/58148222

3 Comments

Why do you have Babel in your package lock json?
And which node and npm do you have?
babel got installed because of tslint requires it and, tslint is a devDependency in the package.json. OS: Windows 10 Pro NodeJs: 8.15.0 NPM: 6.7.0
0

Try a different import syntax, eg.: import { bcrypt } from "bcryptjs";

Other import syntax examples can be found here.

Comments

0

Node.js does not handle ES6 syntax, with imports etc. For that you have to transpile your ES6 code to ES5, you can do it with Babel => https://github.com/babel/example-node-server

If you don't want to use Babel, you can simply replace import by require:

const bcrypt = require("bcryptjs");  // same as 'import * as bcrypt from "bcryptjs";'

1 Comment

Node only handles es6 when used with mjs files, and the experimental flag turned on.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.