Manually Pre-Bundling of Vite
npm install vite-plugin-optimizer手动版的 Vite 预构建



English | 简体中文
- 兼容 Browser, Node.js and Electron
- 自定义 Vite 预构建 Pre-Bundling 内容
``bash`
npm i vite-plugin-optimizer -D
`ts
import optimizer from 'vite-plugin-optimizer'
export default {
plugins: [
optimizer({
vue: const vue = window.Vue; export { vue as default },`
}),
]
}
#### 读取本地文件
`ts`
optimizer({
// 支持嵌套模块命名
// 支持返回 Promise
'@scope/name': () => require('fs/promises').readFile('path', 'utf-8'),
})
#### Node.js 与 Electron
`tsconst { ipcRenderer } = require('electron'); export { ipcRenderer };
optimizer({
// 预构建 ipcRenderer 在 Electron 渲染进程中使用
electron: ,
// 这表示 'fs' 与 'node:fs' 同时支持
// e.g.
// import fs from 'fs'import fs from 'node:fs'
// or
// alias
fs: () => ({
// 这与 行为一致const fs = require('fs'); export { fs as default }
find: /^(node:)?fs$/,
code: ;`
}),
})
将 Node.js ESM 包转换成 CommonJs 模块供 Node.js/Electron 使用
e.g. execa, node-fetch
看看这 👉 vite-plugin-esmodule
optimizer(entries[, options])
`ts`
function optimizer(entries: Entries, options?: OptimizerOptions): import('vite').Plugin;
`ts
export interface OptimizerArgs {
/* 生成缓存文件路径 /
dir: string;
}
export interface ResultDescription {
/**
* 这与 alias 行为一致。import fs from 'fs'
*
* e.g.
* import fs from 'node:fs'
* or
*
*
* @example
* {
* // 这种写法表示同时支持 'fs' 和 'node:fs'。
* find: /^(node:)?fs$/,
* replacement: '/project/node_modules/.vite-plugin-optimizer/fs.js',
* }
*/
alias?: {
find: string | RegExp;
/**
* 如果没有显式的指定,将会使用生成文件的路径作为默认值。
*/
replacement?: string;
};
code?: string;
}
export interface Entries {
[moduleId: string]:
| string
| ResultDescription
| ((args: OptimizerArgs) => string | ResultDescription | Promise
}
export interface OptimizerOptions {
/**
* @default ".vite-plugin-optimizer"
*/
dir?: string;
resolveId?: ((id: string) => string | Promise
}
`
#### 用 Vue 来举个 🌰
`jsconst vue = window.Vue; export { vue as default }
optimizer({
vue: ,`
})
1. 创建 node_modules/.vite-plugin-optimizer/vue.js 文件并包含下面的代码
`js`
const vue = window.Vue; export { vue as default }
2. 创建一个 vue 的别名项,并且添加到 resolve.alias
`js
{
resolve: {
alias: [
{
find: 'vue',
replacement: '/User/work-directory/node_modules/.vite-plugin-optimizer/vue',
},
],
},
}
/**
* 🚧
* 如果你是用的是 function 并且没有返回值, 那么就不会注册 alias
* 这种情况下, 你必须显式的返回 alias
*
* e.g.
*
* optimizer({
* async vue(args) {
*
* // ① 你可能会自己构建 vue 并且输出到指定的文件夹`
* await require('vite').build({
* entry: require.resolve('vue'),
* outputDir: args.dir + '/vue',
* })
*
* return {
* alias: {
* find: 'vue',
* // ② 确保 replacement 指向 Vue 构建后的路径
* replacement: args.dir + '/vue',
* }
* }
* },
* })
*/
3. 默认会将 vue 添加到 optimizeDeps.exclude 中
`jsoptimizeDeps.include
export default {
optimizeDeps: {
// 你可以通过 避开这种行为``
exclude: ['vue'],
},
}