如何更改webpack模块导出要求字符串?

Muh*_*BUL 6 javascript webpack angular angular-builder

例如,当使用webpack创建包时,其输出角度如下。

/* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @angular/core */ "./node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js");

但是我想要输出是这样的:

/* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @angular/core */ "@angular/core");

它在互联网上说您需要更改resolve.alias,但是据我了解,如果更改resolve.alias,这一次我找不到我使用的模块的路径。

我不是很受webpack的支配,但是我确定有解决此问题的方法。有没有可用的解决方案?

const path = require('path');

module.exports = {
    resolve: {
        alias: {
          //I'm stuck there
        }
    }
};
Run Code Online (Sandbox Code Playgroud)

更新

在此处输入图片说明

在以下情况下,就会发生此问题,例如C模块使用X库。同时,此C模块在A模块的子模块A模块下打开。模块A和C在两个不同的项目上编译。我将X库捆绑在模块A中。我没有将X模块捆绑在C模块中。因为我知道在模块A中,该模块X是捆绑在一起的。然而,C模块显影剂得到X模块从基准“ d:\ X-库 ”的文件路径,而A模块开发商自“的X模块参考d:\库\ X库Webpath通过这些引用,从包中调用X模块。最后,当在A模块中打开C模块时,当它想使用X模块时,它会请求“ D:\ X-Library “作为_webpack_require(” D:\ X-Library “)。但是,模块X被模块A注册为_webpack_require(” D:\ Librarires \ X-Library “)。这就是为什么它不起作用的原因。希望我可以,的子模块,模块A和C都编上2个不同的项目。我捆绑X库在模块A内。我不将X模块捆绑在C模块内。因为我知道在模块A中,该模块X是捆绑在一起的。但是,C模块开发人员从“ D:\ X-Library ”文件路径获取X模块引用,而A模块开发人员从“ D:\ Libraries \ X-Library ”文件路径获取X模块引用。有了这些引用,Webpack从捆绑软件中调用X模块。最后,当在A模块中打开C模块时,当它想使用X模块时,它会请求“ D:\ X-Library ”作为_webpack_require(“ D:\ X-Library ”)。但是,模块X被模块A注册为_webpack_require(“ D:\ Librarires \ X-Library”。这就是为什么它不起作用。我希望可以。

Muh*_*BUL 0

对于 Angular 8.3.5 版本,我通过向 webpack 编写插件得到了解决方案。

在 Compliation Hooks 中,模块 id 优化后,如果我更改 id,我可以在创建包之前将其转换为我想要的格式。

module.exports = class ChangeRequireStringPlugin {
    constructor(options) {
        this.options = options;
    }
    apply(compiler) {
        compiler.hooks.compilation.tap('ChangeRequireStringPlugin', compilation => {
            compilation.hooks.afterOptimizeModuleIds.tap('ChangeRequireStringPlugin', (modules) => {
                for (let i = 0; i < this.options.length; i++) {
                    let module = modules.find(s => s.id == this.options[i].path)
                    if (module) {
                        module.id = this.options[i].to;
                    }
                }
            });
        });
    }
};
Run Code Online (Sandbox Code Playgroud)

和 webpack.config.js

const path = require('path');
const ChangeRequireStringPlugin = require("./ChangeRequireStringPlugin/ChangeRequireStringPlugin");
module.exports = {
    plugins: [new ChangeRequireStringPlugin([
        {
            path: "./node_modules/@angular/core/fesm2015/core.js",
            to:"@angular/core"
        }
    ])]
};
Run Code Online (Sandbox Code Playgroud)

这是最好的解决方案吗?我不确定,但他现在正在做我的工作。

Webpack 5 附带了 after Runtime requests 选项。当它到来时,也许最好用钩子来解决。https://webpack.js.org/api/compilation-hooks/#beforeruntimerequirements

我实现此插件的示例项目:https ://github.com/mcantonbul/Angular-Webpack-Change-Require-String