webpack - Babel + WebPack : class properties can't be compiled

标签 webpack babeljs 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" ]
                }
            }

最佳答案

终于找到了问题的原因——webpack配置出现了错误:

include: __dirname + '/components',

由于我的主文件 index.js在根文件夹中与此规则不匹配,我想这会导致我上面描述的错误。
因此,应删除带有“include”选项的这一行以使一切正常

关于webpack - Babel + WebPack : class properties can't be compiled,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49301794/

相关文章:

javascript - 使用vue webpack-simple解析css失败

javascript - 为什么我的箭头函数有原型(prototype)属性?

javascript - 从模块中导出 { default } 不适用于 Jest 中的 Babel 7 和 preset-env

javascript - webpack 如何在项目目录之外的文件上运行 babel-loader?

javascript - 执行 bundle 时使用各自子包的模块

javascript - 使用 es6 react.js 的 Webpack 构建失败

babeljs - 什么是 babel 预设?舞台是什么意思?

javascript - 插件/预设文件不允许导出对象,只能导出函数。删除并保留 babel 安装?使用 webpack 选择?

node.js - 使用 Webpack 构建 Angular 2 for NPM 包

javascript - 使用 Node 6.3 设置 Koa 2