[错误]_找不到模块 'babel-preset-es2015'

[Error]_Cannot find module 'babel-preset-es2015'

我正在学习为我的 React 项目设置 Webpack。然后,当我 运行 这个命令

时,我在 Babel 设置步骤遇到错误

npx webpack --config webpack.config.js

Module build failed (from ./node_modules/babel-loader/lib/index.js):
Error: Cannot find module 'babel-preset-es2015'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:636:15)
at resolve (internal/modules/cjs/helpers.js:33:19)
at resolveStandardizedName (...\project\node_modules\@babel\core\lib\config\files\plugins.js:111:7)      
at resolvePreset (...\project\node_modules\@babel\core\lib\config\files\plugins.js:59:10)
at loadPreset (...\project\node_modules\@babel\core\lib\config\files\plugins.js:78:20)
at loadPreset.next (<anonymous>)
at createDescriptor (...\project\node_modules\@babel\core\lib\config\config-descriptors.js:187:16)       
at createDescriptor.next (<anonymous>)
at step (...\project\node_modules\gensync\index.js:261:32)
at evaluateAsync (...\project\node_modules\gensync\index.js:291:5)

更详细一点,我有一些代码行:

webpack.config.js

const path = require('path');

module.exports = {
  mode: 'development',
  entry: path.resolve(__dirname, 'src', 'index.js'),
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js'
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          { loader: "style-loader" },
          { loader: "css-loader" }
        ]
      },
      {
        test: /\.(jsx|js)$/,
        include: path.resolve(__dirname, 'src'),
        exclude: /node_modules/,
        use: [{
          loader: 'babel-loader',
          options: {
            presets: [
              ['@babel/preset-env', {
                "targets": "defaults"
              }],
              '@babel/preset-react'
            ]
          }
        }]
      }
    ],
  }
}

.babelrc

{
  "presets": ["es2015", "react"]
}

package.json

{
  "name": "react",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@babel/core": "^7.16.7",
    "@babel/preset-env": "^7.16.7",
    "@babel/preset-react": "^7.16.7",
    "antd": "^4.17.3",
    "babel-loader": "^8.2.3",
    "react": "^16.11.0",
    "react-dom": "^16.11.0",
    "react-scripts": "3.2.0",
    "webpack": "^5.65.0",
    "webpack-cli": "^4.9.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "devDependencies": {
    "css-loader": "^6.5.1",
    "ts-loader": "^9.2.6"
  }
}

如何解决这个问题,有什么注意事项? 非常感谢!

您的问题来自不正确的 .babelrc 文件,请仔细查看 - 您将 babel 定义为使用“2015”预设,但您的依赖项指出您使用的是“@babel/preset-env”。

在您的情况下,“2015”的正确替换为“@babel/preset-env”。阅读更多: https://babeljs.io/docs/en/babel-preset-env

.babelrc

{
  "presets": ["@babel/preset-env", "react"]
}