Working on my amazing, incredible, life-changing Chrome extension, I noticed there wasnβt much documentation available in terms of how to use manifest v3 extensions in conjunction with Webpack to modularize code. So hereβs a pretty quick guide.
(you can also just skip to the GitHub repository if youβre into that sort of thing)
Write your code:
import { Example } from './example.js'
const example = new Example()
class Example {
constructor() {
console.log('hello world')
}
}
export {
Example
}
Setup your webpack.config.js file and run webpack:
const path = require('path');
module.exports = {
mode: 'production',
entry: './src/index.js',
// This will output a single file under `dist/bundle.js`
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
}
}
> webpack
asset bundle.js 76 bytes [compared for emit] [minimized] (name: main)
orphan modules 112 bytes [orphan] 1 module
./src/index.js + 1 modules 183 bytes [built] [code generated]
webpack 5.28.0 compiled successfully in 177 ms
Create your service worker entrypoint, importing the produced bundle:
try {
// This is the file produced by webpack
importScripts('dist/bundle.js');
} catch (e) {
// This will allow you to see error logs during registration/execution
console.error(e);
}
Reference the file in your manifest:
{
"name": "webpack-manifest-v3-example",
"author": "Theodore Brockman",
"version": "1.0.0",
"description": "A Chrome extension packed using Webpack.",
"permissions": [],
"background": {
"service_worker": "service-worker.js"
},
"manifest_version": 3
}
Load your unpacked extension and inspect the service worker view to check the output:
Done.