首页 > 解决方案 > Webpack Unexpected Token / 没有文件类型的加载器

问题描述

我有一个无法使用 WebPack 构建的纯 JavaScript 应用程序。我删除了所有内容,直到只剩下这些行:

class MyClass {
    doStuff = (abc) => {

    }
}

我收到的错误消息如下:

ERROR in ./src/js/mapdata.js 2:12
Module parse failed: Unexpected token (2:12)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| class MyClass {
>     doStuff = (abc) => {
|
|     }

我的 webpack.config 看起来像这样:

const path = require('path');

module.exports = {
    entry: './src/js/mapdata.js',
    output: {
        filename: 'rwmaps.js',
        path: path.resolve(__dirname, 'dist'),
    },
    module: {
        rules: [
            { test: /\.json$/, use: 'json-loader' }
        ]
    }
};

我不知道问题是什么。如果我直接从网页(使用 )访问 JS,它就可以正常工作。有任何想法吗?

标签: javascriptwebpack

解决方案


您可能缺少 babel 加载器和类属性。尝试在 package.json 中添加以下依赖项

"@babel/core": "^7.10.1",    "@babel/plugin-proposal-class-properties": "^7.10.1",    "@babel/preset-env": "^7.10.1",    "babel-loader": "^8.1.0"

此外,创建.babelrc并添加以下代码:

{
  "plugins": ["@babel/plugin-proposal-class-properties"]
}

最后,使用以下规则更新 webpack.config.js 文件:

    { test: /\.m?js$/,
      exclude: /(node_modules)/,
      use: {
        loader: 'babel-loader',
        options: {
          presets: ['@babel/preset-env']
        }
      }
    }

我希望它有帮助!


推荐阅读