首页 > 解决方案 > Webpack 覆盖 require 的行为

问题描述

我有一个在我的 webpack 期间导入的模块,它执行如下操作:

'use strict';

module.exports = {
  position: true,
  gfm: true,
  commonmark: false,
  footnotes: false,
  pedantic: false,
  blocks: require('./block-elements.json')
};

Webpack 像这样重写这个模块:

module.exports = {
  position: true,
  gfm: true,
  commonmark: false,
  footnotes: false,
  pedantic: false,
  blocks: __webpack_require__(/*! ./block-elements.json */     "./block-elements.json")
};

然后另一个函数假设blocks成员是一个字符串。

有没有办法覆盖webpack_require的编写并将其替换为我自己的将 json 加载到字符串中的函数?

标签: jsonwebpack

解决方案


最后通过编写我自己的加载器并明确设置模块导出的默认属性来修复。

// Code for the loader
module.exports = function(source) {

  // Just inline the source and fix up defaults so that they don't
  // mess up the logic in the setOptions.js file
  return `module.exports = ${source}\nmodule.exports.default = false`;
}

另一个脚本正在枚举返回对象的键,而“默认”键把它弄乱了。但是,如果密钥具有布尔类型,它将允许它通过。

具体来说,用于在反应控件中托管降价的 remark-parser 库存在问题。


推荐阅读