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

如何编写自定义Loader以避免Webpack内置JSON Loader自动执行?

Got it, let's walk through exactly how to build this custom Webpack loader that turns JSON configs into JavaScript code—while avoiding the built-in JSON loader from interfering.

Step 1: Why the built-in JSON loader is getting in your way

Webpack’s built-in JSON loader automatically handles .json files by parsing them into JavaScript objects. But since you want to generate custom JS code from the JSON (not just parse it), we need to tell Webpack to treat the output of your loader as JavaScript, not JSON. The key here is overriding the module type for your target JSON files.

Step 2: Write your custom loader

Create a file called json-to-js-loader.js in your project root. This loader will read the raw JSON string, parse it, then generate the JavaScript code you need. Here’s a practical example that converts the JSON config into an exported object plus a helper function:

module.exports = function(source) {
  // Parse the input JSON string into a JS object
  const config = JSON.parse(source);

  // Generate your custom JavaScript code
  // Adjust this to fit your specific needs—this is just a template
  const generatedCode = `
    // Auto-generated from your JSON config
    export const config = ${JSON.stringify(config, null, 2)};

    // Example helper function to access config values
    export const getConfigValue = (key) => {
      if (!config.hasOwnProperty(key)) {
        console.warn(\`Config key "\${key}" does not exist\`);
        return null;
      }
      return config[key];
    };
  `;

  // Return the generated JS code—this will go to babel-loader next
  return generatedCode;
};

Step 3: Configure Webpack to use your loader

In your webpack.config.js, you need to:

  • Target your JSON config files (use a specific pattern like .config.json to avoid breaking other JSON files)
  • Chain your custom loader before babel-loader
  • Disable the built-in JSON loader by setting type: 'javascript/auto'

Here’s the config snippet:

const path = require('path');

module.exports = {
  // ... other webpack configs
  module: {
    rules: [
      {
        // Target only your config JSON files (adjust the test pattern as needed)
        test: /\.config\.json$/,
        // Chain loaders: your custom loader runs first, then babel-loader
        use: [
          'babel-loader',
          path.resolve(__dirname, './json-to-js-loader.js')
        ],
        // This tells Webpack to treat the output as JavaScript, not JSON
        // Disables the built-in JSON loader entirely for these files
        type: 'javascript/auto'
      }
    ]
  }
};

Step 4: Test it out

Create a sample config file, say app.config.json:

{
  "apiBaseUrl": "https://your-api.com/v1",
  "maxRetries": 3,
  "enabledFeatures": ["notifications", "analytics"]
}

Then import it in a JavaScript file:

import { config, getConfigValue } from './app.config.json';

console.log(config.apiBaseUrl); // Logs "https://your-api.com/v1"
console.log(getConfigValue('maxRetries')); // Logs 3

When you run Webpack, your custom loader will convert the JSON to JS code, which babel-loader will process normally—no built-in JSON loader interference.

内容的提问来源于stack exchange,提问作者M Miller

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:16:10