vite-plugin-externals
English | 简体中文
use to external resources, like webpack externals, but only use in browser now.
Can be used in production
mode without other rollup
configuration.
but it will not take effect by default in commonjs
, such as ssr
.
Usage
npm i vite-plugin-externals -D
Add it to vite.config.js
import { viteExternalsPlugin } from 'vite-plugin-externals'
export default {
plugins: [
viteExternalsPlugin({
vue: 'Vue',
react: 'React',
'react-dom': 'ReactDOM',
lazy: ['React', 'lazy']
}),
]
}
Warning: If you loaded production
libray in vite dev mode
, may make HMR
fail.
Eg.
<script src="./vue.global.prod.js"></script>
<script src="./vue.global.js"></script>
How to work
transform source code of js file.
viteExternalsPlugin({
vue: 'Vue',
}),
import Vue from 'vue'
const Vue = window['Vue']
import { reactive, ref as r } from 'vue'
const reactive = window['Vue'].reactive
const r = window['Vue'].ref
import * as vue from 'vue'
const vue = window['Vue']
export { useState as _useState } from 'react'
export const _useState = window['React'].useState
Warning: please use the plugin after converting to JS code, because the plugin only transform JS code. Eg.
import vue from '@vitejs/plugin-vue'
export default {
plugins: [
vue(),
viteExternalsPlugin({
vue: 'Vue',
}),
]
}
Configuration
filter
The files in node_modules
are filtered by default, and only transform js/ts/vue/jsx/tsx file.
You can specify the filter
function. Return true
will be transform to external.
viteExternalsPlugin({
vue: 'Vue',
}, {
filter(code, id, ssr) {
return false
}
}),
useWindow
set false
, the window
prefix will not be added.
Warning: If your module name has special characters, such as /
, set useWindow option false
, will throw error.
viteExternalsPlugin({
vue: 'Vue',
}, { useWindow: false }),
import Vue from 'vue'
const Vue = Vue