我正在开发简单的 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" ]
}
}