Add BrowserSync in your Vite project.
This plugin supports Vite 4 and 5.
proxy
and snippet
modedev
, preview
or build --watch
npm i -D vite-plugin-browser-sync
# yarn
yarn add -D vite-plugin-browser-sync
# pnpm
pnpm add -D vite-plugin-browser-sync
# bun
bun add -D vite-plugin-browser-sync
By default, BrowserSync will start alongside your Vite Server in dev
. It uses the proxy
mode of BrowserSync based on your Vite server options : no need to pass any options to make it works!
// vite.config.js / vite.config.ts
import VitePluginBrowserSync from 'vite-plugin-browser-sync'
export default {
plugins: [VitePluginBrowserSync()]
}
If you want to manage BrowserSync or override default behavior of this plugin, you can pass a bs
object with your BrowserSync options in it :
// vite.config.js / vite.config.ts
import VitePluginBrowserSync from 'vite-plugin-browser-sync'
export default {
plugins: [
VitePluginBrowserSync({
dev: {
bs: {
ui: {
port: 8080
},
notify: false
}
}
})
]
}
If you need the snippet
mode of BrowserSync, the plugin supports it by injecting the script automatically.
// vite.config.js / vite.config.ts
import VitePluginBrowserSync from 'vite-plugin-browser-sync'
export default {
plugins: [
VitePluginBrowserSync({
dev: {
mode: 'snippet'
}
})
]
}
You can also enable the plugin on vite build --watch
mode and vite preview
mode.
[!IMPORTANT]
- In
buildWatch
, if you use the defaultproxy
mode you need to set thebs
object.snippet
mode is available inbuildWatch
but it is not recommanded to use since it update yourindex.html
file.- In
preview
, only theproxy
mode is supported since it will not inject thesnippet
.
// vite.config.js / vite.config.ts
import VitePluginBrowserSync from 'vite-plugin-browser-sync'
export default {
plugins: [
VitePluginBrowserSync({
dev: {
enable: false,
},
preview: {
enable: true,
},
buildWatch: {
enable: true,
bs: {
proxy: 'http://localhost:3000',
}
}
})
]
}
[!NOTE] For Astro user, this plugin is not working in preview mode because of overrides made by Astro.
This plugin overrides default options from BrowserSync to doesn't duplicate behaviors already handle by ViteJS. Futhermore, your ViteJS config are synced with BrowserSync.
If you want to change the overrided options you free to do so via the bs
object.
Option | Why | dev | buildWatch | preview |
---|---|---|---|---|
logLevel | Set to silent , use ViteJS printUrls to display BrowserSync info |
✔️ | ✔️ | ✔️ |
open | Apply ViteJS open option | ✔️ | ✔️ | |
codeSync | Disabled because it is already handle by ViteJS | ✔️ | ||
online | Synced with the server host option | ✔️ | ✔️ |
proxy
modeOption | Why | dev | buildWatch | preview |
---|---|---|---|---|
proxy.target | Inject the right url from ViteJS | ✔️ | ✔️ | |
proxy.ws | Force websocket proxy to make work ViteJS HMR | ✔️ | ✔️ |
snippet
modeOption | Why |
---|---|
logSnippet | Handle by the plugin so no need to display the snippet |
snippet | The snippet injection is handle by the plugin |
MIT