webpack plugin to inject built assets into a file
mightyplow 9693d11442 1.1.1 | 6 سال پیش | |
---|---|---|
lib | 6 سال پیش | |
.gitignore | 6 سال پیش | |
README.md | 6 سال پیش | |
index.js | 6 سال پیش | |
package-lock.json | 6 سال پیش | |
package.json | 6 سال پیش |
A plugin for webpack 4 which replaces assets with it's output filenames in other assets. It was created to be used for caching in service workers.
The plugin comes in handy when you add hashes to your assets during the webpack build.
It can also be used in watch mode.
npm i -D @mightyplow/inject-assets-webpack-plugin
The assets you want to be replaced have to be wrapped in double curly braces. The assets can only be replaced if the target is also a webpack asset.
So for example if you want to replace the assets in a service worker, it has either be built by webpack or at least run through another plugin. Personally I like to use the copy-webpack-plugin to copy the service worker to the target directory.
If there are multiple files for the same asset name, for example when you have a css file and a js file with the same asset name, you can specify the wanted asset by adding a pipe symbol and the file extension.
[
'{{vendor|js}}',
'{{vendor|css}}'
]
These are the asset names in which you want the placeholders to be replaced.
Let's assume, our service worker has the following content
// serviceWorker.js
const FILES_TO_CACHE = [
'/',
'{{vendor}}',
'{{app|js}}'
'{{app|css}}'
]
// webpack.config.js
const CopyPlugin = require('copy-webpack-plugin');
const InjectAssetsPlugin = require('@mightyplow/inject-assets-webpack-plugin');
...
plugins: [
new CopyPlugin([
{
from: './src/serviceWorker.js',
to: './'
}
]),
new InjectAssetsPlugin({
targets: ['serviceWorker.js']
})
]
...
// webpack.config.js
const InjectAssetsPlugin = require('@mightyplow/inject-assets-webpack-plugin');
...
entry: {
// build the app and the service worker with webpack
app: path.join(__dirname, 'src', 'index.js'),
serviceWorker: path.join(__dirname, 'src', 'serviceWorker.js')
},
plugins: [
new InjectAssetsPlugin({
// replace assets in the service worker and in the app script;
// since there would also be an app css asset, we have to specify the type here
targets: ['serviceWorker', 'app|js']
})
]
...
// index.js
if ('serviceWorker' in navigator) {
// {{serviceWorker}} will be replaced with the built file name
navigator.serviceWorker.register('{{serviceWorker}}')
.then((registration) => {
console.info('service worker registered');
});
}