寻求Vue Cli中__non_webpack_require__的替代实现方案
Got it, let's tackle this problem. Since Vue CLI is built on Webpack under the hood, we have a couple of solid alternatives to replace __non_webpack_require__ that let you load metadata at runtime without bundling the target module.
externals Configuration This approach lets you explicitly tell Webpack to exclude specific modules from the bundle, relying on the runtime environment's native module loader (like Node.js require) to load them.
Update your
vue.config.js:
Add theexternalsfield to the Webpack configuration to exclude your metadata file. For example, if your metadata is ametadata.jsonfile in your project root:module.exports = { configureWebpack: { externals: { './metadata.json': 'commonjs ./metadata.json' } } }Adjust the path and module type (
commonjshere for Node-like environments) to match your setup.Load the metadata in your code:
Just use a regularrequirecall—Webpack won't bundle the file, and it'll be loaded at runtime:const metadata = require('./metadata.json');
Note: This works best for Node.js, Electron, or other environments with a native require function. For pure browser-based projects, this won't work since browsers don't have built-in require.
webpackIgnore Comment A more lightweight option that doesn't require config changes—you can directly tell Webpack to skip parsing a specific require call with a special comment.
In your code, add the /* webpackIgnore: true */ comment right before the require statement:
// Webpack will ignore this require call during bundling const metadata = /* webpackIgnore: true */ require('./path/to/metadata.json');
How it works:
This comment is a Webpack-specific directive that disables static analysis for that require line. The file won't be included in your bundle, and the runtime environment will use its native module loader to fetch it at startup.
For Browser Environments:
If you're building a pure frontend app (no Node.js runtime), browsers don't support require, so you'll need to switch to using fetch to load the metadata as a static asset:
async function loadMetadata() { // Make sure your metadata file is in the public directory so it's copied to dist const response = await fetch('/metadata.json'); const metadata = await response.json(); return metadata; } // Call this function when your app starts loadMetadata().then(metadata => { // Use your metadata here });
In this case, the file isn't bundled (it's served as a separate static asset), which aligns with your requirement of not packing the module into the main bundle.
内容的提问来源于stack exchange,提问作者Drogo

