【问题标题】:Module parse failed: Unexpected character '@'模块解析失败:意外字符“@”
【发布时间】:2018-09-23 12:47:24
【问题描述】:

我想构建我的 graphql 服务器应用程序,当我通过 webpack 4 构建时,我在 typeorm 的装饰器上遇到了这个错误:

ERROR in ./src/models/user.ts 15:0
Module parse failed: Unexpected character '@' (15:0)
You may need an appropriate loader to handle this file type.
| import { JWT } from './jwt';
| 
> @Entity()
| @Unique(['username'])
| @Unique(['email'])
 @ ./src/server.ts 15:0-37 34:45-49

webpack.config.js 是这样的:

var ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
var fs = require('fs');
var path = require('path');
var nodeExternals = require('webpack-node-externals');

module.exports = {
  mode: 'production',
  entry: './src/server.ts',
  output: {
    path: __dirname + '/dist',
    filename: '[name].[chunkhash:8].js',
  },
  resolve: {
    extensions: ['.ts', '.tsx', '.js'],
  },
  module: {
    rules: [
      {
        test: '/\.tsx?$/',
        exclude: '/node_modules/',
        include: path.resolve(__dirname, 'src'),
        use: {
          loader: 'ts-loader',
          options: {
            transpileOnly: true
          }
        }
      }
    ]
  },
  plugins: [
    new ForkTsCheckerWebpackPlugin()
  ],
  externals: [nodeExternals()],
};

tsconfig.json 是这样的:

{
  "exclude": [
    "fixtures",
    "tests"
  ],
  "compilerOptions": {
    "target": "es2016",
    "module": "commonjs",
    "outDir": "dist",
    "rootDir": "src",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": ["es2016", "esnext.asynciterable"]
  }
}

当我使用 tsc 编译时,我没有任何错误,但是当我通过 node dist/server.js 启动应用程序时出现此错误:

(function (exports, require, module, __filename, __dirname) { import { Field, ID, Int, ObjectType } from 'type-graphql';
SyntaxError: Unexpected token {

你能帮我解决这个错误吗? 感谢提前

【问题讨论】:

    标签: node.js typescript webpack


    【解决方案1】:

    看起来ts-loader 没有被使用。我认为这是因为您已将 test 指定为字符串而不是正则表达式。尝试删除周围的单引号。请参阅the documentation 中的示例。

    【讨论】:

    • 非常感谢您的回答。但实际上在编译之后,我得到了与使用 tsc 相同的错误: (function (exports, require, module, __filename, __dirname) { import { Field, ID, Int, ObjectType } from 'type-graphql'; SyntaxError:意外的令牌{有解决此错误的想法吗?
    • 你为什么同时使用 webpack 和 tsc?无论如何,问题在于dist/server.js 中有 ES6 模块语法。假设 tsc 实际上正在使用您的 tsconfig.json 文件(例如,您运行的是 tsctsc -p .,而不是 tsc src/server.ts),这不应该发生,因为您的 tsconfig.json 文件指定了 "module": "commonjs"。如果您需要更多帮助,请发布一个可以为您重现问题的存储库。
    • 再次感谢您的回复,这里是repository 来重现此错误
    • 好的,我已经有了存储库,我已经运行了npm install。现在我需要运行什么命令来重现错误?
    • 我能够重现错误!在ormconfig.json 中将src/models/**/*.ts 更改为dist/models/**/*.js 修复了它并给了我另一个错误DataTypeNotSupportedError: Data type "json" in "User.roles" is not supported by "sqlite" database.。希望当您在使用 postgres 数据库的环境中尝试此更改时,您会走得更远。
    猜你喜欢
    • 1970-01-01
    • 2022-12-31
    • 2017-04-04
    • 2019-07-18
    • 2019-05-20
    • 2017-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多