3
votes

I have set up a pretty plain project with express, node.js and webpack. After installing TypeORM when configuring webpack.config.js it triggers unexpected token error for User.ts in entity folder.

The problem seems to be related to the fact that ormconfig.json is referring to .ts entity files.

Solution in similar threads seems to be using ts-node with some extra parameters, but I am using webpack in this project and executing the bundle file.

index.ts

import 'reflect-metadata';
import { createConnection } from 'typeorm';
import { User } from './entity/User';
createConnection()
    .then(async connection => {
        console.log('Inserting a new user into the database...');
        const user = new User();
        user.firstName = 'Timber';
        user.lastName = 'Saw';
        user.age = 25;
        await connection.manager.save(user);
        console.log('Saved a new user with id: ' + user.id);

        console.log('Loading users from the database...');
        const users = await connection.manager.find(User);
        console.log('Loaded users: ', users);

        console.log(
            'Here you can setup and run express/koa/any other framework.'
        );
    })
    .catch(error => console.log(error));

ormconfig.json

{
    "type": "mssql",
    "host": "*",
    "port": 27017,
    "username": "*",
    "password": "*",
    "database": "*",
    "synchronize": true,
    "logging": false,
    "entities": ["src/entity/**/*.ts"],
    "migrations": ["src/migration/**/*.ts"],
    "subscribers": ["src/subscriber/**/*.ts"],
    "cli": {
        "entitiesDir": "src/entity",
        "migrationsDir": "src/migration",
        "subscribersDir": "src/subscriber"
    }
}

webpack.config.js

module.exports = {
    mode: 'development',
    entry: path.resolve(path.join(__dirname, './src/index.ts')),
    externals: [nodeExternals()],
    name: 'API',
    context: __dirname,
    target: 'node',
    output: {
        path: __dirname + '/dist',
        filename: '[name].bundle.js',
        publicPath: '/',
        libraryTarget: 'commonjs2',
    },
    resolve: {
        extensions: ['.ts', '.tsx', '.js', '.json'],
        modules: [path.resolve(__dirname, 'node_modules')],
    },
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                loader: 'awesome-typescript-loader',
                exclude: [/node_modules/, /dist/],
            },
            {
                test: /\.js$/,
                loader: 'babel-loader',
                exclude: [/node_modules/, /dist/],
                options: {
                    babelrc: true,
                },
            },
        ],
    },
    plugins: [new CleanWebpackPlugin()],
};

Error messages are as following (the code reference is the default user entity file that comes with TypeORM

api/src/entity/User.ts:1
(function (exports, require, module, __filename, __dirname) { import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
                                                                     ^

SyntaxError: Unexpected token {
    at new Script (vm.js:80:7)
    at createScript (vm.js:274:10)
    at Object.runInThisContext (vm.js:326:10)
    at Module._compile (internal/modules/cjs/loader.js:664:28)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
    at Module.load (internal/modules/cjs/loader.js:600:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
    at Function.Module._load (internal/modules/cjs/loader.js:531:3)
    at Module.require (internal/modules/cjs/loader.js:637:17)
    at require (internal/modules/cjs/helpers.js:22:18)
2

2 Answers

5
votes

I found a solution from yesterday by Soufiaane that did not cover the webpack aspect, but solves the problem nonetheless.

Delete the ormconfig.json file and pass the database config in the createConnection function.

import { User } from './entity'
// import every other entity you have
// .......

await createConnection({
        type: 'sqlite',
        database: 'database.sqlite',
        synchronize: true,
        logging: true,
        entities: [
            User // pass your entities in here
        ]
    })
0
votes

This is because you are calling the global version of typeorm which expects javascript you need to be calling typeorm through ts-node like:

./node_modules/.bin/ts-node ./node_modules/.bin/typeorm

I set up an alias in my .bashrc:

alias tstypeorm='./node_modules/.bin/ts-node ./node_modules/.bin/typeorm'

This solution works well for me (running on OsX)

(You could also change the directories in your ormconfig.json to point to the generated javascript files)