【问题标题】:Webpack compile config.js to config.jsonWebpack 将 config.js 编译为 config.json
【发布时间】:2017-11-30 05:10:04
【问题描述】:

有没有办法编译例如从 config.js 这个:

module.exports = {
 param: 'value',
 param1: 'value2'
}

将其编译成 JSON 格式到 config.json 文件中用于输出.. 一些加载器?

【问题讨论】:

    标签: javascript json webpack compilation config


    【解决方案1】:

    这是你要找的吗?

    var myConfig = {
     param: 'value',
     param1: 'value2'
    };
    
    console.log(JSON.stringify(myConfig)); // You can delete this if you want.
    
    fs = require('fs');
    fs.writeFile('config.json', JSON.stringify(myConfig), function (err) {
        if (err) {
            return console.log(err);
        }
    });
    
    module.exports = myConfig;
    

    【讨论】:

    • 谢谢!那是。但它不适用于 webpack。 config.json 没有被创建,也许有一些 webpack 解决方案?
    【解决方案2】:

    解决了!这对于一个名为extract-text-webpack-plugin 的模块来说非常简单,只需添加到module.rules 一个规则即可。 Webpack 示例配置:

    const ExtractTextPlugin = require('extract-text-webpack-plugin');
    module.exports = {
        entry: "./app.js"
        output: {
            filename: "bundle.js"
        },
        module: {
            rules: [{
                test: /\.json\.js/,
                // extract the text
                use: ExtractTextPlugin.extract({
                    use: {}
                })
            }]
        },
        plugins: [
            new ExtractTextPlugin('config.json', {
                // some options if you want
            })
        ]
    }
    

    在 config.json.js 文件上导出时不要忘记对对象进行字符串化。应该是这样的:

    module.exports = JSON.stringify({
        param: 'value',
        param1: 'value2'
    });
    

    也就是说,希望它对某人有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-23
      • 2018-07-01
      • 2019-12-05
      • 2019-01-26
      • 1970-01-01
      • 2016-12-31
      • 2020-05-24
      相关资源
      最近更新 更多