簡體   English   中英

如何修復 Webpack 和 Babel 的“require is not defined”錯誤?

[英]How do I fix "require is not defined" error with Webpack and Babel?

我不斷收到錯誤Uncaught ReferenceError: require is not defined in browser even with WebpackBabel 出於某種原因,我以前從未擔心過這個問題。 我不確定這個錯誤是由更新的軟件包還是什么引起的。 為了簡單起見,我設置了一個非常簡單的測試應用程序。 package.json

{
   "name": "require-test",
   "version": "1.0.0",
   "description": "",
   "main": "index.js",
   "engines": {
      "node": "16.16.0"
   },
   "scripts": {
      "build": "webpack --config webpack.config.js"
   },
   "author": "",
   "license": "ISC",
   "devDependencies": {
      "@babel/core": "^7.18.10",
      "@babel/preset-env": "^7.18.10",
      "babel-loader": "^8.2.5",
      "webpack": "^5.74.0",
      "webpack-cli": "^4.10.0"
   }
}

webpack.config.js

const path = require('path');

module.exports = {
   target: "node",
   mode: "production",
   output: {
      path: path.resolve(__dirname, 'dist'),
      clean: true,
      filename: (pathData) => {
         return 'index.js'
      },
   },
   module: {
      rules: [
         {
            test: /\.m?js$/,
            exclude: /(node_modules|bower_components)/,
            use: {
               loader: 'babel-loader',
               options: {
                  presets: ['@babel/preset-env']
               }
            }
         }
      ]
   }
}

src/index.js (構建前的 js 文件)

const path = require('path');

console.log(path);

dist/index.js (構建后的js文件)

(()=>{var r,e={17:r=>{"use strict";r.exports=require("path")}},t={};r=function r(o){var s=t[o];if(void 0!==s)return s.exports;var p=t[o]={exports:{}};return e[o](p,p.exports,r),p.exports}(17),console.log(r)})();

您的代碼有幾處需要更改。 首先,當您在瀏覽器上運行錯誤的代碼時,您不能以構建nodetarget 其次, path是專門為在節點服務器上運行而設計和構建的,但是,在瀏覽器上有一個后備路徑,稱為path-browserify 您可以查看其文檔以了解其工作原理。

無論如何總結一下,最后你需要切換targetweb

module.exports = {
 target: "web",
 // ...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM