带有 Babel 的 Webpack 给出了未捕获的 referenceError: require is not defined

时间:2021-03-12 10:08:41

标签: javascript reactjs webpack babeljs babel-loader

我使用以下设置配置了 Webpack:

module.exports = {
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: ["babel-loader"]
            }
        ]
    },
    mode: 'development'
};

还有babel.config.json

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

转译工作正常,但在浏览器中启动页面后,出现以下错误: Uncaught ReferenceError: require is not defined

package.json

{
  "name": "test",
  "version": "0.0.1",
  "description": "test",
  "main": "main.js",
  "scripts": {
    "css-build": "node-sass _sass/main.scss dist/main.css",
    "css-deploy": "npm run css-build && npm run css-postcss",
    "css-postcss": "postcss --use autoprefixer --output dist/main.css dist/main.css",
    "css-watch": "npm run css-build -- --watch",
    "deploy": "npm run css-deploy && npm run js-build",
    "js-build": "babel _javascript --out-dir dist",
    "js-watch": "npm run js-build -- --watch",
    "start": "npm-run-all --parallel css-watch js-watch",
    "build": "webpack"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/cli": "^7.13.10",
    "@babel/core": "^7.13.10",
    "@babel/preset-env": "^7.13.10",
    "@babel/preset-react": "^7.12.13",
    "autoprefixer": "^9.7.6",
    "babel-loader": "^8.2.2",
    "babel-preset-env": "^1.7.0",
    "babel-preset-es2015-ie": "^6.7.0",
    "node-sass": "^4.13.1",
    "npm-run-all": "^4.1.5",
    "postcss-cli": "^7.1.0",
    "webpack": "^5.24.4",
    "webpack-cli": "^4.5.0"
  },
  "dependencies": {
    "leaflet": "^1.7.1",
    "lodash": "^4.17.21",
    "react": "^17.0.1",
    "react-dom": "^17.0.1"
  }
}

我尝试了很多方法,但对我的问题没有任何帮助。

1 个答案:

答案 0 :(得分:0)

module.exports = {
entry: './app/index.js', // add this in webpack config
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: ["babel-loader"]
            }
        ]
    },
    mode: 'development'
};