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)