Manually Pre-Bundling of Vite
English | 简体中文
- Compatible Browser, Node.js and Electron
- Custom Vite Pre-Bundling content
npm i vite-plugin-optimizer -D
import { defineConfig } from 'vite'
import optimizer from 'vite-plugin-optimizer'
export default defineConfig({
plugins: [
optimizer({
vue: `const vue = window.Vue; export { vue as default }`,
}),
]
})
optimizer({
// Support nested module id
// Support return Promise
'@scope/name': () => require('fs/promises').readFile('path', 'utf-8'),
})
optimizer({
// Optimize Electron for use ipcRenderer in Renderer-process
electron: `const { ipcRenderer } = require('electron'); export { ipcRenderer };`,
// this means that both 'fs' and 'node:fs' are supported
// e.g. `import fs from 'fs'` or `import fs from 'node:fs'`
fs: () => ({
// this is actually `alias.find`
find: /^(node:)?fs$/,
code: `const fs = require('fs'); export { fs as default }`;
}),
})
Such as execa, node-fetch, you can see this 👉 vite-plugin-esmodule
export interface Entries {
[moduleId: string]:
| string
| ResultDescription
| ((args: OptimizerArgs) => string | ResultDescription | Promise<string | ResultDescription | void> | void)
| void;
}
export interface OptimizerArgs {
/** Generated file cache directory */
dir: string;
}
export interface ResultDescription {
alias?: { find: string | RegExp; replacement: string };
code?: string;
}
export interface OptimizerOptions {
/**
* @default ".vite-plugin-optimizer"
*/
dir?: string;
/**
* @default ".js"
*/
ext?: string;
}
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 toresolve.alias
{
resolve: {
alias: [
{
find: 'vue',
replacement: '/User/work-directory/node_modules/.vite-plugin-optimizer/vue',
},
],
},
}
/**
* 🚧
* If you are using a function and have no return value, alias will not be registered.
* In this case, you must explicitly specify alias.
*
* e.g.
*
* optimizer({
* vue(args) {
* // You can customize the build "vue" and output it to the specified folder.
* // e.g.
* build({
* entry: require.resolve('vue'),
* outputDir: args.dir + '/vue',
* })
*
* return {
* alias: {
* find: 'vue',
* replacement: args.dir + '/vue',
* }
* }
* },
* })
*/
- Add
vue
to theoptimizeDeps.exclude
by default.
You can avoid it byoptimizeDeps.include
export default {
optimizeDeps: {
exclude: ['vue'],
},
}