1

延迟加载,具有适当的依赖解析,没有全局变量。

假设我有三个模块,mainlazydepmain和导入。lazy_ 可能需要也可能不需要在某个时间点加载。如何将 webpack 配置为:depmainlazy

  1. 捆绑main在一起dep(好吧,这很容易)
  2. 单独捆绑lazy,没有dep. 当它加载时,它会depmain包中解析。
  3. 无需在窗口或全局命名空间中写入任何内容

我可以找到如何做(2)或(3),但不能同时做。

当我使用时,SplitChunksPlugin我得到 (2) 而没有 (3) - 输出写入window.webpackJsonP全局命名空间。出于我的目的,这很糟糕,原因有两个。我必须支持没有window对象的 DOMLess 环境,而且我的项目是一个在其他人的网站/应用程序上运行的库/小部件,所以我不能让全局变量到处乱放。

当我将它配置为两个入口点时,我得到 (3) 而没有 (2) - 我的lazy文件包含dep模块代码,这似乎是多余的。

// index.js / entrypoint
import Main from "./Main.js";
new Main().sayHi().doStuff();

// Main.js
import Dep from "./Dep.js";

export default class Main extends Dep {
  constructor() {
    super();
    this.name = "Main";
  }

  doStuff() {
    import("./Lazy.js")
      .then(module => {
        let lazy = new module.default();
        lazy.sayHi();
      })
      .catch(err => {
        console.log(`owch: ${err.message}`);
      });
    }
}

// Lazy.js
import Dep from "./Dep.js";

export default class Lazy extends Dep {
  constructor() {
    super();
    this.name = "Lazy";
  }
}

// Dep.js
export default class Dep {
  constructor() {
    this.name = "Dep";
  }

  sayHi() {
    console.log(`hello, my name is ${this.name}`);
    return this;
  }
}
4

0 回答 0