在使用Webpack4和Babel7构建React应用时,我遇到了以下错误。
ERROR in ./src/index.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
Error: Cannot find module 'babel-preset-react' from '/Users/me/Desktop/reflask'
- If you want to resolve "react", use "module:react"
- Did you mean "@babel/react"?
at Function.module.exports [as sync] (/Users/me/Desktop/reflask/node_modules/resolve/lib/sync.js:43:15)
at resolveStandardizedName (/Users/me/Desktop/reflask/node_modules/@babel/core/lib/config/files/plugins.js:101:31)
at resolvePreset (/Users/me/Desktop/reflask/node_modules/@babel/core/lib/config/files/plugins.js:58:10)
at loadPreset (/Users/me/Desktop/reflask/node_modules/@babel/core/lib/config/files/plugins.js:77:20)
at createDescriptor (/Users/me/Desktop/reflask/node_modules/@babel/core/lib/config/config-descriptors.js:154:9)
at items.map (/Users/me/Desktop/reflask/node_modules/@babel/core/lib/config/config-descriptors.js:109:50)
at Array.map (<anonymous>)
at createDescriptors (/Users/me/Desktop/reflask/node_modules/@babel/core/lib/config/config-descriptors.js:109:29)
at createPresetDescriptors (/Users/me/Desktop/reflask/node_modules/@babel/core/lib/config/config-descriptors.js:101:10)
at passPerPreset (/Users/me/Desktop/reflask/node_modules/@babel/core/lib/config/config-descriptors.js:58:96)
@ multi (webpack)-dev-server/client?http://localhost:8080 ./src main[1]
我尝试过使用以下命令删除 node_modules 文件夹并重新安装依赖项。终端
rm -rf node_modules/
npm install
配置
package.json
{
"name": "reflask",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server --open --mode development",
"build": "webpack"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@babel/core": "^7.1.0",
"@babel/preset-env": "^7.1.0",
"@babel/preset-react": "^7.0.0",
"babel-loader": "^8.0.2",
"html-loader": "^0.5.5",
"html-webpack-plugin": "^3.2.0",
"prop-types": "^15.6.2",
"webpack": "^4.19.1",
"webpack-cli": "^3.1.1",
"webpack-dev-server": "^3.1.9"
},
"dependencies": {
"bootstrap": "^4.1.3",
"react": "^16.5.2",
"react-bootstrap": "^0.32.4",
"react-dom": "^16.5.2",
"react-router-dom": "^4.3.1"
}
}
webpack.config.js
const HtmlWebPackPlugin = require("html-webpack-plugin");
module.exports = {
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
presets: ['react']
}
}
},
{
test: /\.html$/,
use: [
{
loader: "html-loader"
}
]
}
]
},
plugins: [
new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "./index.html"
})
]
};
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './js/components/App.jsx';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();
.babelrc
:Babel配置文件。{
"presets": ["@babel/preset-env", "@babel/preset-react"]
}