添加类字段时,“模块解析失败:意外的令牌”

时间:2018-11-15 06:48:13

标签: node.js typescript webpack

使用Webpack成功构建了以下TypeScript代码(这意味着可以使用静态类字段和其他TypeScript功能):

export default class ConfigRepresentative {
  constructor() {
    console.log('ok');
  }
}

失败(与删除privatestatic相同):

export default class ConfigRepresentative {

  private static ownInstanceHasBeenCreated: boolean = false;

  constructor() {
    console.log('ok');
  }
}

错误:

ERROR in ./TypeScriptSource/index.ts 7:10
Module parse failed: Unexpected token (7:10)
You may need an appropriate loader to handle this file type.
| export default class ConfigRepresentative {
| 
>   private static ownInstanceHasBeenCreated: boolean = false;
| 
|   constructor() {

webpack.config.js

module.exports = {

  entry: './TypeScriptSource/index.ts',
  output: {
    filename: 'index.js',
    path: __dirname,
    libraryTarget: 'umd'
  },

  target: 'node',
  mode: 'production',
  watch: true,

  module: {
    rules: [
      {
        test: /\.ts?$/,
        use: 'ts-loader',
        exclude: /node_modules/
      }
    ]
  },
  resolve: {
    extensions: ['.ts', '.js']
  }
};

为了节省您的时间来重现此问题,我附加了souse文件。 error.zip

1 个答案:

答案 0 :(得分:0)

这是因为项目位于node_modules文件夹中。设置exclude: /node_modules/取消规则{test: /\.ts?$/, use: 'ts-loader'},但是没有类属性代码的是纯JavaScript。

(我知道这是不好的做法-在node_modules内部进行开发,但是我不知道用于开发依赖关系的其他解决方案。在这种情况下,如果单个ConfigRepresentative确实没有用,未被其他项目使用。

相关问题