Skip to content

Instantly share code, notes, and snippets.

@amygrinn
Last active September 27, 2020 17:00
Show Gist options
  • Save amygrinn/0721b08a622e3023c4f8bfe816638ede to your computer and use it in GitHub Desktop.
Save amygrinn/0721b08a622e3023c4f8bfe816638ede to your computer and use it in GitHub Desktop.
Webpack write to file
/** @type {import('webpack').Configuration} */
/**
* Write the version of the package to a file named 'latest'
* When uploaded to a server with multiple versions, you can
* get the name of the latest by running `curl https://<server>/latest`
*/
const WritePlugin = require('./build-tools/write-webpack-plugin');
const { version } = require('./package.json');
module.exports = {
...,
plugins: [
new WritePlugin({
filename: 'latest',
data: version,
}),
],
...,
};
// Included as a dependency of webpack: https://github.com/webpack/webpack/blob/master/package.json
/* eslint-disable import/no-extraneous-dependencies */
const { RawSource } = require('webpack-sources');
const PLUGIN_NAME = 'Write Webpack Plugin';
/**
* Write some text to a file through the process of a webpack build
* @class WritePlugin
*/
class WritePlugin {
/**
* @param options.filename the name of the file to put in the output directory
* @param options.data the data to write to the file
*/
constructor(options = {}) {
this.options = options;
this.source = new RawSource(options.data);
}
apply(compiler) {
compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => {
compilation.hooks.additionalAssets.tap(
PLUGIN_NAME,
() => compilation.emitAsset(this.options.filename, this.source),
);
});
}
}
module.exports = WritePlugin;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment