Generate Asset Webpack Plugin

raw JSON →
0.3.0 verified Sat Apr 25 auth: no javascript maintenance

Webpack plugin (v0.3.0) for dynamically generating asset files (like index.html) during compilation, with access to compilation info. Lightweight alternative to html-webpack-plugin with a callback-based API. Released 2015, no recent updates; works with Webpack 1-3 but not v4+. Suitable for simple HTML generation without templating.

error TypeError: GenerateAssetPlugin is not a constructor
cause Incorrect import: destructured instead of default require.
fix
Use const GenerateAssetPlugin = require('generate-asset-webpack-plugin');
error Error: Cannot find module 'generate-asset-webpack-plugin'
cause Package not installed or typo in package name.
fix
Run npm install --save-dev generate-asset-webpack-plugin and check node_modules.
breaking Webpack 4+ no longer supports plugins using old compilation hooks; this plugin does not work with Webpack 4+.
fix Use html-webpack-plugin or another plugin compatible with Webpack 4+.
gotcha cb must be called exactly once; failure to call cb will hang the build.
fix Always invoke cb(null, content) or cb(error) in the fn callback.
gotcha extraFiles is not well documented; files listed must exist in compilation.assets or they will be ignored.
fix Ensure extraFiles entries are already present in the compilation or use another plugin to add them.
npm install generate-asset-webpack-plugin
yarn add generate-asset-webpack-plugin
pnpm add generate-asset-webpack-plugin

Shows creating a Webpack config that generates an index.html as an asset, using the plugin's callback API.

const GenerateAssetPlugin = require('generate-asset-webpack-plugin');
const webpack = require('webpack');

const compiler = webpack({
  entry: './src/index.js',
  output: { path: './dist', filename: 'bundle.js' },
  plugins: [
    new GenerateAssetPlugin({
      filename: 'index.html',
      fn: (compilation, cb) => {
        const chunk = compilation.chunks[0];
        const jsFile = chunk.files[0];
        const html = `<!DOCTYPE html><html><head><title>App</title></head><body><script src="${jsFile}"></script></body></html>`;
        cb(null, html);
      },
      extraFiles: ['favicon.ico']
    })
  ]
});

compiler.run((err, stats) => {
  if (err) console.error(err);
  console.log(stats.toString({ colors: true }));
});