vite-plugin-optimizer
Manually Pre-Bundling of Vite
English | 简体中文
- Compatible Browser, Node.js and Electron
- Custom Vite Pre-Bundling content
Install
npm i vite-plugin-optimizer -D
Usage
import optimizer from 'vite-plugin-optimizer'
export default {
plugins: [
optimizer({
vue: `const vue = window.Vue; export { vue as default }`,
}),
]
}
Load a local file
optimizer({
'@scope/name': () => require('fs/promises').readFile('path', 'utf-8'),
})
Node.js and Electron
optimizer({
electron: `const { ipcRenderer } = require('electron'); export { ipcRenderer };`,
fs: () => ({
find: /^(node:)?fs$/,
code: `const fs = require('fs'); export { fs as default };`
}),
})
Advance
Optimize Node.js ESM packages as CommonJs modules for Node.js/Electron.
e.g. execa, node-fetch
You can see 👉 vite-plugin-esmodule
API (Define)
optimizer(entries[, options])
function optimizer(entries: Entries, options?: OptimizerOptions): import('vite').Plugin;
export interface OptimizerArgs {
dir: string;
}
export interface ResultDescription {
alias?: {
find: string | RegExp;
replacement?: string;
};
code?: string;
}
export interface Entries {
[moduleId: string]:
| string
| ResultDescription
| ((args: OptimizerArgs) => string | ResultDescription | Promise<string | ResultDescription | void> | void);
}
export interface OptimizerOptions {
dir?: string;
resolveId?: ((id: string) => string | Promise<string | void> | void);
}
How to work
Let's use Vue as an example
optimizer({
vue: `const vue = window.Vue; export { vue as default }`,
})
- Create
node_modules/.vite-plugin-optimizer/vue.js
and contains the following code
const vue = window.Vue; export { vue as default }
- Register a
vue
alias item and add it to resolve.alias
{
resolve: {
alias: [
{
find: 'vue',
replacement: '/User/work-directory/node_modules/.vite-plugin-optimizer/vue',
},
],
},
}
- Add
vue
to the optimizeDeps.exclude
by default.
export default {
optimizeDeps: {
exclude: ['vue'],
},
}