TypeORM + Webpack 导致 SyntaxError: Unexpected token for entity file [英] TypeORM + Webpack causes SyntaxError: Unexpected token for entity file

查看:35
本文介绍了TypeORM + Webpack 导致 SyntaxError: Unexpected token for entity file的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

问题似乎与 ormconfig.json 指的是 .ts 实体文件这一事实有关.

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

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

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

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

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自带的默认用户实体文件

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)

推荐答案

我昨天通过 Soufiaane 找到了一个解决方案没有覆盖 webpack 方面,但解决了问题.

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

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

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

这篇关于TypeORM + Webpack 导致 SyntaxError: Unexpected token for entity file的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆