Babel + WebPack:无法编译类属性

5

我正在开发一个简单的JavaScript应用,但在使用Babel和Webpack时遇到了问题 - 类(静态)属性无法编译,会抛出错误:

ERROR in ./components/comp1.js
Module parse failed: Unexpected token (2:18)
You may need an appropriate loader to handle this file type.
| export class Comp1 {
|     static states = '123';
| }

我用以下方法简化了出现问题的文件,只有两个 - 入口点index.js:

import { Comp1 } from './components/comp1'
export const components = {
    Comp1
};

组件的外观如下:

export class Comp1 {
    static states = {
        first: 1,
        second: 2
    };
}

最令人困惑的时刻是它在我的OSX机器上成功编译,但在Win 10 PC上无法运行。我不知道操作系统如何影响......

我在package.json中有以下依赖项:

  "devDependencies": {
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.4",
    "babel-plugin-transform-class-properties": "^6.24.1",
    "babel-preset-env": "^1.6.1",
    "webpack": "^4.1.1",
    "webpack-cli": "^2.0.12"
  }

还有webpack.config文件:

module.exports = function(env) {
    var config = {
        entry: { 'bundle': './index.js' },
        output: {
            filename: '[name].js',
            path: __dirname + '/dist',
            libraryTarget: 'var',
            library: 'ns'
        },
        devtool: 'source-map',
        resolve: { extensions: ['.js', '.json'] },
        module: {
            rules: [
                {
                    test: /\.js$/,
                    include: __dirname + '/components',
                    exclude: /(node_modules|bower_components)/,
                    use: {
                        loader: 'babel-loader'
                    }
                }
            ]
        }
    };

    return config;
};

并且.babelrc:

{
  "plugins": [ "transform-class-properties" ],
  "presets": [ "env" ]
}

更新

我也尝试将 Babel 设置移到 webpack.config.js 中,但是并没有帮助:

            use: {
                loader: 'babel-loader',
                options: {
                    presets: ['env'],
                    plugins: [ "transform-class-properties" ]
                }
            }
1个回答

3
最后,我找到了问题的原因 - webpack 配置中有错误:
include: __dirname + '/components',

自从我的主文件index.js在根目录下不符合此规则,我猜这导致了我上面描述的错误。 因此,应该只需删除带有 "include" 选项的这行代码即可使一切正常运行。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接