我安装了webpack,这是我的webpack.config
const path = require('path');
const HtmlWebPackPlugin = require('html-webpack-
plugin');
const MiniCssExtractPlugin = require('mini-css-extract-
plugin');
module.exports ={
mode:'development',
entry:'./src/scripts/app.js',
output:{path: path.resolve(__dirname,'dist') ,
filename:'bundle.js'},
module:{rules:[
{
test:/\.jsx?/i,
exclude:/node_modules/i,
use:{
loader:'babel-loader',
options:{
presets:['@babel/preset-env']
}
}
},
{
test:/\.s?css?/i,
use:[
{
loader:MiniCssExtractPlugin.loader,
options:{
publicPath:'/dist'
}
},
'css-loader',
'sass-loader'
]
}
]},
plugins:[
new HtmlWebPackPlugin({
template:'./src/index.html',
filename:'index.html'
}),
new MiniCssExtractPlugin({
filename:'main.css'
})
]
}
这是我的package.json
{
"name": "webp",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "test",
"build": "webpack"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@babel/core": "^7.2.2",
"@babel/preset-env": "^7.3.1",
"babel-loader": "^8.0.5",
"css-loader": "^2.1.0",
"html-webpack-plugin": "^3.2.0",
"mini-css-extract-plugin": "^0.5.0",
"node-sass": "^4.11.0",
"sass-loader": "^7.1.0",
"webpack": "^4.29.3",
"webpack-cli": "^3.2.3"
},
"dependencies": {
"react": "^16.8.1",
"react-dom": "^16.8.1"
}
}
但是它不能编译jsx。给我这个错误
class myHeading extends React.Component{
6 | render(){
> 7 | return <h1> A header will be rendered
here</h1>
| ^
8 | }
9 | }
10 |
在我的课程中,我遵循与朋友相同的路径,他们没有问题进行安装,但是我不知道我的安装有什么问题。 有人可以帮我吗?将会非常感谢。
答案 0 :(得分:0)
您需要@babel/preset-react
才能转换jsx。您可以使用以下脚本通过NPM或Yarn安装它:
# NPM
npm i -D @babel/preset-react
# Yarn
yarn add -D @babel/preset-react
您还需要将预设添加到babel加载器中,如下所示:
const path = require("path");
const HtmlWebPackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
mode: "development",
entry: "./src/scripts/app.js",
output: { path: path.resolve(__dirname, "dist"), filename: "bundle.js" },
module: {
rules: [
{
test: /\.jsx?/i,
exclude: /node_modules/i,
use: {
loader: "babel-loader",
options: {
presets: ["@babel/preset-env", "@babel/preset-react"]
}
}
},
{
test: /\.s?css?/i,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
publicPath: "/dist"
}
},
"css-loader",
"sass-loader"
]
}
]
},
plugins: [
new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "index.html"
}),
new MiniCssExtractPlugin({
filename: "main.css"
})
]
};