Enable hot reloading for content script and background script (service worker) in MV3.
yarn add mv3-hot-reload
// webpack.config.ts
const isDev = process.env.NODE_ENV === 'development'
/**
* @param entryType specify the entry type for different entry names than 'content' or 'background'
*/
function getEntry(name: string, entryType?: 'content' | 'background') {
return [path.join(srcDir, name), ...(isDev ? [`mv3-hot-reload/${entryType ?? name}`] : [])]
}
const webpackConfig = {
// ...
entry: {
// ...
background: getEntry('background'),
content: getEntry('content'),
anotherContentScript: getEntry('anotherContentScriptFolder', 'content'),
},
}
The code for hot reloading will only execute when process.env.NODE_ENV === 'development'
.
// background.ts
import 'mv3-hot-reload/background'
// your code...
// content.ts
import 'mv3-hot-reload/content'
// your code...
Example:
"watch:src": "webpack --config webpack/webpack.dev.js --watch",
+ "watch:dist": "mv3-hot-reload",
+ "dev": "concurrently yarn:watch:*",
module.exports = {
// Specify the port of hot reload server, defaults to 9012
port: 9012,
// Specify the directory you want to watch, defaults to 'dist'
directory: 'dist',
// Specifies an array of filenames that should be excluded in watched directory
exclude: [],
}
If you want to set the port, you also need to expose it with process.env.MV3_HOT_RELOAD_PORT
to
the client side.
An example:
// webpack.config.js
const config = require('./mv3-hot-reload.config')
module.exports = {
// ...
plugins: [
new webpack.EnvironmentPlugin({
MV3_HOT_RELOAD_PORT: config.port,
}),
],
}
pacexy/chrome-extension-typescript-starter
The implementation of hot reloading in mv3 refers to theprimone/violet.
MIT