You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

寻求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.

Alternative 1: Use Webpack 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.

  1. Update your vue.config.js:
    Add the externals field to the Webpack configuration to exclude your metadata file. For example, if your metadata is a metadata.json file in your project root:

    module.exports = {
      configureWebpack: {
        externals: {
          './metadata.json': 'commonjs ./metadata.json'
        }
      }
    }
    

    Adjust the path and module type (commonjs here for Node-like environments) to match your setup.

  2. Load the metadata in your code:
    Just use a regular require call—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.

Alternative 2: Use the 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 23:57:43