Webpack 4打包后浏览器报错__webpack_require__ is not defined求助
Hey there, let’s work through this error step by step—this is a common gotcha with Webpack 4, and we can nail it down with a few checks:
1. Audit Your Output Configuration
The __webpack_require__ function is part of Webpack’s core runtime, so misconfigured output settings often cause it to go missing:
- Double-check
output.libraryTarget: If you’re building a regular web app (not a library), leave this as the default value. If you are building a library, use valid options like'umd'or'commonjs2'—avoid'var'unless you explicitly need it, as it can prevent the runtime from being injected properly. - Verify
output.publicPath: This should match the URL path where your bundle is served. For example, if your bundle lives in a rootdistfolder, setpublicPath: '/dist/'; if it’s in the root directory, usepublicPath: '/'. Mismatched paths can prevent the runtime script from loading entirely.
2. Validate Your Entry Points
A broken entry setup can stop Webpack from generating the full runtime:
- Confirm your entry file path is correct: Use relative paths like
./src/index.js(instead ofsrc/index.js) to avoid path resolution issues, and make sure the file actually exists at that location. - If using multiple entries: Ensure you’re not accidentally excluding the main entry that should carry the Webpack runtime. Avoid overcomplicating entry configurations unless you have a specific need.
3. Check How Your Bundle Is Loaded in HTML
If your HTML isn’t pulling in the bundle correctly, the runtime code will never run:
- If using
HtmlWebpackPlugin: Let the plugin inject the bundle automatically—don’t manually add a<script>tag for your bundle. Duplicate tags can cause conflicts that break the runtime. - If adding the script manually: Match the
srcattribute to youroutput.publicPathandoutput.filename. For example, if your bundle isdist/main.js, the tag should be<script src="/dist/main.js"></script>.
4. Rule Out Conflicting Plugins/Loaders
Some tools can interfere with Webpack’s runtime injection:
- Temporarily disable aggressive optimizations: Webpack 4 enables
ModuleConcatenationPluginby default in production mode—try turning it off to see if the error vanishes. - Check custom loaders: Minifiers or transpilers that strip "unnecessary" code might accidentally remove the Webpack runtime. Test with a basic loader setup (e.g., just
babel-loader) to isolate the issue.
Quick Isolation Test
If you’re stuck, create a minimal Webpack config to test if the error persists:
module.exports = { entry: './src/index.js', output: { filename: 'main.js', path: __dirname + '/dist', publicPath: '/' } };
Build with this config and load the app. If the error is gone, gradually add back your original config settings to find which one is causing the problem.
内容的提问来源于stack exchange,提问作者Prad9

