Webpack插件:如何在构建时读取插件使用者的文件?

问题描述

是否可以读取安装了Webpack插件的回购的内容?

本质上,我编写了一个特定的JS library,它要求调用者在其应用程序代码中使用require.context,以便在构建时读取一些文件并将它们传递给库:

import Library from 'library';

new Library({
  requires: require.context('./foo',false,/\w+\.js$/),});

我想减轻用户的负担,只需在库中进行require.context调用即可将API简化为此:

import Library from 'library';

new Library();

但是,它不起作用,因为该库不知道何时运行应用程序代码的Webpack构建。

我尝试在库中编写一个Webpack插件:

const path = require('path');

class TestPlugin {
  apply(compiler) {
    compiler.hooks.beforeRun.tap('TestPlugin',() => {
      console.log(
        `Path where webpack was executed: ${compiler.options.context}`
      );
    });
  }
}

module.exports = {
  ...
  plugins: [new TestPlugin()],};

但是,只有在构建库本身时才调用此函数,而在构建应用程序时才调用

如何将require.context调用移到库中(这是NPM依赖项),仍然让它读取调用者的文件?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...