Webpack 4出现ReferenceError: require is not defined错误求助
ReferenceError: require is not defined Issue Hey there, let's break down why you're hitting this error and get it sorted out step by step.
What's Causing the Problem?
Looking at your webpack.config.js, the core issue comes from conflicting rules for .js files:
- You're using both
script-loaderandbabel-loaderon all.jsfiles.script-loaderis designed to run JS as global, non-modular scripts—it doesn't process CommonJS syntax likerequire, leaving those calls untouched in your bundled code. - Browsers don't have a built-in
requirefunction, so when yourbundle.jsruns in the browser, it throws that error immediately. - Having overlapping rules for the same file type also makes webpack process your code in conflicting ways, worsening the problem.
Step-by-Step Fixes
1. Remove the Unnecessary script-loader Rule
If your main.js uses modular code (like require calls to import other files or packages), you don't need script-loader at all. Delete that entire rule from your config. Here's your cleaned-up webpack.config.js:
const path = require('path'); const webpack = require('webpack'); module.exports = { mode: 'production', entry: { main: ['./src/js/main.js'] }, output: { path: path.resolve(__dirname, './src/js/'), filename: 'bundle.js', }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use:[{ loader: 'babel-loader', options: { presets: ['@babel/preset-env'] } // Note: 'env' is outdated—use the new package name }] }, ] }, target: 'web' };
2. Update Your Babel Dependencies (Optional but Recommended)
The env preset you're using is an older version of Babel's preset. It's now officially named @babel/preset-env, so make sure your dependencies are up to date:
npm install --save-dev @babel/core @babel/preset-env babel-loader
3. Double-Check Your main.js Syntax
Ensure any require calls in main.js target valid modules—either local files or npm packages. For example:
// Example main.js code const helper = require('./helper.js'); // Local module const moment = require('moment'); // NPM package
4. Verify Your HTML Script Tag
Make sure you're correctly linking to the bundled bundle.js in your HTML file:
<script src="./src/js/bundle.js"></script>
If You Do Need script-loader (For Legacy Code)
If you have a specific non-modular script (like an old library that doesn't support imports) that needs script-loader, don't mix it with your modular code rule. Instead, target that specific file separately:
module: { rules: [ // Handle modular JS files { test: /\.js$/, exclude: /node_modules|legacy-script\.js/, // Exclude the file needing script-loader use:[{ loader: 'babel-loader', options: { presets: ['@babel/preset-env'] } }] }, // Handle the legacy global script { test: /legacy-script\.js$/, use: ['script-loader'] } ] }
This keeps modular and global code processing separate, avoiding the require error entirely.
内容的提问来源于stack exchange,提问作者Tester

