【问题标题】:WebPack: replace 'require' result with {}WebPack:用 {} 替换 'require' 结果
【发布时间】:2018-03-25 05:48:55
【问题描述】:

我的 TypeScript 代码中有一个基类,它接受一个对象作为参数之一。我有很多扩展这个基类的类。这看起来像:

class Finances extends I18nBase {
    constructor(){
        super(require('./finances.tran.json'));
    }
}

我已经使用这种方法为我的站点创建和调试 i18n。现在我需要摆脱生产代码中的 json 片段。但我想关闭它们,而不是完全从代码中删除它们,好像我以后可能需要它们。

所以我尝试了 WebPack IgnorePlugin,但它给了我Cannot find module "./finances.tran.json" 错误。

有没有办法在构建阶段用{} 替换tran\.json 中的所有require

更新

用这样的虚拟.json文件解决了这个问题:

plugins: [
    new webpack.NormalModuleReplacementPlugin(/tran\.json$/, 
        path.resolve(__dirname, srcRoot, 'empty_tran.json'))
]

【问题讨论】:

    标签: typescript webpack webpack-2


    【解决方案1】:

    您也许可以使用 string-replace-loader 之类的东西来替换字符串。

    module: {
      loaders: [
        {
          test: /\.ts$/,
          loader: 'string-replace',
          query: { 
            search: '.\.\/finances\.tran\.json', replace: '{}',
            flags: 'g' 
          }
        }
      ]
    }
    

    或者其他一些正则表达式,而不是我在这里用来覆盖大量 json 文件的那个。

    【讨论】:

      【解决方案2】:

      用这样的虚拟.json 文件解决了这个问题:

      plugins: [
          new webpack.NormalModuleReplacementPlugin(/tran\.json$/, 
              path.resolve(__dirname, srcRoot, 'empty_tran.json'))
      ]
      

      【讨论】:

        猜你喜欢
        • 2021-05-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-18
        • 2016-01-29
        • 1970-01-01
        • 2016-05-25
        • 2016-01-30
        • 2013-09-05
        相关资源
        最近更新 更多