TypeORM + Webpack导致SyntaxError:实体文件的意外令牌

时间:2019-06-26 09:39:00

标签: node.js typescript webpack typeorm

我已经用express,node.js和webpack建立了一个非常普通的项目。在配置webpack.config.js时安装TypeORM后,它会触发实体文件夹中User.ts的意外令牌错误。

问题似乎与ormconfig.json引用.ts实体文件有关。

类似线程中的解决方案似乎正在使用带有一些额外参数的ts-node,但是我在此项目中使用了webpack并执行了捆绑文件。

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()],
};

错误消息如下(代码参考是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 个答案:

答案 0 :(得分:0)

昨天Soufiaane我找到了一个解决方案,该解决方案没有涵盖webpack方面,但是仍然解决了该问题。

删除ormconfig.json文件,并在createConnection函数中传递数据库配置。

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
        ]
    })

答案 1 :(得分:0)

这是因为您正在调用typeorm的全局版本,该版本需要javascript,您需要通过ts-node调用typeorm,例如:

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

我在.bashrc中设置了别名:

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

此解决方案对我来说很好(在OsX上运行)

(您也可以将ormconfig.json中的目录更改为指向生成的javascript文件)