我正在 webpack-dev-server 上测试 React 项目。我想使用类字段语法,但在状态初始化时出错。
client:162 ./src/containers/App.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: Missing class properties transform.
2 |
3 | class App extends Component {
4 | state = {
| ^
5 | count: 0
6 | }
7 | // constructor(props) {
我找到了预设的解决方案 this "presets": ["es2015", "stage-0", "react"]
。但我正在使用“env”预设。我认为“env”预设支持所有 babel-stages。我必须更改预设吗?
应用程序.js
class App extends Component {
state = {
count: 0
}
render() {
return (
<div>
<input defaultValue={this.state.count} />
</div>
);
}
}
export default App;
包.json
{
"name": "redux",
"version": "1.0.0",
"description": "",
"main": "counter.js",
"dependencies": {
"@types/react": "^16.4.14",
"babel": "^6.23.0",
"babel-loader": "^7.1.5",
"babel-preset-env": "^1.7.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"babel-register": "^6.26.0",
"http": "0.0.0",
"react": "^16.5.2",
"react-dom": "^16.5.2",
"webpack": "^4.19.1",
"webpack-cli": "^3.1.0",
"webpack-dev-server": "^3.1.9"
},
"scripts": {
"devserver": "webpack-dev-server --open --progress"
},
"author": "",
"license": "ISC",
"devDependencies": {
"babel-plugin-transform-class-properties": "^6.24.1"
}
}
.babelrc
{
"presets": ["env", "react"],
"plugins": ["transform-class-properties"]
}
.webpack.config.js
const webpack = require('webpack');
const path = require('path');
module.exports = {
mode: 'development',
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
publicPath: '/dist/',
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.js$/,
include: path.join(__dirname),
exclude: /(node_modules)|(dist)/,
use: {
loader: 'babel-loader',
options: {
presets: ['env']
}
}
}
]
}
}