Skip to content

Commit 7251ae1

Browse files
committed
docs: farewell-webpack
1 parent fc41c2c commit 7251ae1

File tree

1 file changed

+162
-0
lines changed

1 file changed

+162
-0
lines changed

docs/farewell-webpack.md

Lines changed: 162 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,162 @@
1+
# Farewell Webpack
2+
3+
随着 Web 应用体量的增长,需要处理的代码量也随之增长,Webpack 的机制 —— 加载所有模块(即使有缓存)进行打包再提供, 已经显得力不从心。
4+
5+
随着浏览器原生支持 ES 模块(包括在 Web Worker 中), 至少在开发阶段,我们已经不再需要模块打包。
6+
7+
当然,由于 JSX 和其他预编译的需求的存在,对每个文件进行单独转换的需求依然存在。 而在最终生产环境,浏览器版本多样,对语言特性的支持并不都是完整, 部署所需的代码,依然需要降级处理或者添加 Polyfill。
8+
9+
基于上述背景,Vite 及其背靠的 Rollup 生态,可以更好地满足我们的 Web 应用开发和构建需求。
10+
11+
## Vite 的两种形态
12+
13+
### `vite build`
14+
15+
这一形态,基本就是 `rollup build`,但由于 Vite 插件 `enforce``apply` 的配置,最终生效的插件和顺序需要注意。 如果要定义最终构建过程,我们可以完全当做 Rollup 来配置或者开发 Plugin.
16+
17+
插件的生命周期两个阶段:
18+
19+
* `build`: <https://rollupjs.org/guide/en/#build-hooks>
20+
* `output-generation`: <https://rollupjs.org/guide/en/#output-generation-hooks>
21+
22+
### `vite serve`
23+
24+
在这一形态下, vite 没有 `output-generation` 阶段,并是根据请求文件地址,找到并直接返回文件内容, 当然如果需要预编译,也会触发 Rollup 的 `build` Hooks.
25+
26+
所以,当我们企图直接使用 Rollup 的插件,如果该插件使用到了 `refID = this.emitFile({})``import.meta.ROLLUP_FILE_URL_${refID}`
27+
(会通过 `output-generation` 阶段的 [`resolveFileUrl` Hook](https://rollupjs.org/guide/en/#resolvefileurl) 替换成对应生成文件) ,
28+
29+
该插件 Rollup 是无法在 `vite serve` 这一形态生效的。
30+
31+
虽然,Vite 提供了额外的占位符 `__VITE_ASSET__${hash}__`,但我们可以有更好的方式, 去做到 Rollup 插件 的兼容 —— 利用 `build`
32+
阶段的 [`transform` Hook](https://rollupjs.org/guide/en/#transform)
33+
34+
当处于 `vite serve` 形态时,我们调用 `resolveFileUrl`/`resolveImportMeta``renderChunk`, 并且在注册 Rollup 插件 的时候,代理一下 `emitFile`
35+
,这样便可基本能做到兼容 Rollup 插件 了。
36+
37+
## 生产构建
38+
39+
### 需要 ES5 怎么办?Babel 正值当年!
40+
41+
这点和 Webpack 一样,我们只需要让 Babel 帮我们将代码转换为 ES5 和 ESModule 的代码即可。 这样只是多了一步预编译罢了,并不会太破坏 Vite 的机制,两种形态均适用。
42+
43+
```ts
44+
import { babel as rollupBabel } from "@rollup/plugin-babel";
45+
46+
export default defineConfig[{
47+
plugins: [
48+
{
49+
// 非常需要注意这里,要在确保在 Vite 核心插件前运行
50+
enforce: "pre",
51+
...rollupBabel({
52+
babelrc: true,
53+
babelHelpers: "runtime",
54+
exclude: "node_modules/**",
55+
}),
56+
}
57+
]
58+
}]
59+
```
60+
61+
### 不支持 ES 模块怎么办? AMD/RequireJS 尚能饭否!
62+
63+
首先 `vite serve` 形态是不需要的, 只需要再 `vite build` 形态做修改即可,当然,编写为 Rollup 插件可以让使用更方便。
64+
65+
```ts
66+
67+
export default outputAMD = () => {
68+
let config
69+
let requireJSRef
70+
71+
return {
72+
name: "my-vite-plugin/output-amd",
73+
74+
configResolved(c) {
75+
config = c;
76+
},
77+
78+
// 构建开始打首先打包好 request.js
79+
async buildStart() {
80+
if (config.command !== "build") {
81+
return undefined;
82+
}
83+
84+
const data = await transformRequireJS();
85+
86+
requireJSRef = this.emitFile({
87+
name: "require.js",
88+
source: data.code,
89+
type: "asset",
90+
});
91+
92+
return undefined;
93+
},
94+
95+
// 修改 rollup 的 output format 为 amd
96+
outputOptions(o) {
97+
if (config.command !== "build") {
98+
return undefined;
99+
}
100+
101+
o.format = "amd";
102+
o.amd = {
103+
autoId: true,
104+
};
105+
return o;
106+
},
107+
108+
// 替换 index html 的 js 文件并额外插入 require.js 依赖
109+
transformIndexHtml(html, { bundle }) {
110+
if (config.command !== "build") {
111+
return undefined;
112+
}
113+
114+
const entryFile = getEntry(bundle);
115+
const requireJSFile = getFilenameByName(bundle, "require.js");
116+
117+
const $ = cheerio.load(html, {});
118+
119+
$(`script[type=module]`).remove();
120+
$(`link[rel=modulepreload]`).remove();
121+
122+
$("head").append(`<script src="${config.base}${requireJSFile}"></script>`);
123+
$("body").append(`<script src="${config.base}${entryFile}"></script>`);
124+
125+
return $.html();
126+
},
127+
128+
// 入口文件需要调用一下对应模块,并配置 baseUrl
129+
renderChunk(code: string, chunk: RenderedChunk, options: NormalizedOutputOptions) {
130+
if (options.format === "amd" && chunk.isEntry) {
131+
let prefix = "";
132+
let params = paramsOf(chunk.facadeModuleId || "")
133+
134+
// 在 web worker
135+
// 同样需要插入 require.js 依赖, 通过 importScripts
136+
if (params.has("worker")) {
137+
prefix = `importScripts("${config.base}${this.getFileName(requireJSRef)}");`;
138+
// 由于 amd 生成代码有 define wrap 的存在,
139+
// 我们确保 onmessage 在文件 root 上
140+
// `self.addEventListener('message', (evt) => {})` 或者 `self.onmessage = (evt) => {}`
141+
code = hoistOnMessage(code)
142+
}
143+
return `
144+
${prefix}
145+
requirejs.config({ baseUrl: "${config.base}" });
146+
${code}
147+
require(["${chunk.fileName.replace(/\.js$/, "")}"]);
148+
`;
149+
}
150+
return code;
151+
},
152+
}
153+
}
154+
```
155+
156+
## 杂项
157+
158+
* 图片字体等,已内置
159+
* VendorGroups: 可以通过实现 <https://rollupjs.org/guide/en/#outputmanualchunks>
160+
* PWA: <https://github.com/antfu/vite-plugin-pwa>
161+
* MonacoEditor: <https://github.com/vitejs/vite/discussions/1791#discussioncomment-321046>
162+

0 commit comments

Comments
 (0)