Babel + WebPack:无法编译类属性

时间:2018-03-15 14:14:57

标签: webpack babel babel-loader

我正在处理简单的js应用程序,我遇到了与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" ]
}

UPD

我也尝试将babel设置移动到webpack.config.js,但它没有帮助:

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

1 个答案:

答案 0 :(得分:1)

最后,我发现了问题的原因 - 在webpack配置中出现了错误:

include: __dirname + '/components',

由于根文件夹中的主文件index.js与此规则不匹配,我猜它会导致我上面描述的错误。 所以这一行与#34;包括"应该删除选项以使一切工作