xz64 / license-webpack-plugin

Outputs licenses from 3rd party libraries to a file
ISC License
165 stars 51 forks source link

Does not add a banner on webpack 5 #101

Closed andrian2111 closed 3 years ago

andrian2111 commented 3 years ago

Minimal reproduction:

package.json

{
  "name": "example",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "build": "WEBPACK_ENV=production NODE_ENV=production webpack"
  },
  "private": true,
  "devDependencies": {
    "jquery": "3.6.0",
    "license-webpack-plugin": "2.3.18",
    "webpack": "5.37.0",
    "webpack-cli": "4.7.0"
  }
}

app.js

import * as $ from 'jquery'
console.log($)

webpack.config.js

const LicenseWebpackPlugin = require('license-webpack-plugin').LicenseWebpackPlugin

module.exports = {
  mode: 'production',
  entry: './app.js',
  plugins: [
    new LicenseWebpackPlugin({
      addBanner: true,
      renderBanner: () => `/*! BANNER */`
    })
  ]
}

The output file does not contain the banner described in webpack.config.js.

This problem may be caused by a webpack bug, but I'm not a specialist in this matter. A quick fix is to put the banner generating code outside the webpack hook (https://github.com/xz64/license-webpack-plugin/blob/master/src/WebpackCompilerHandler.ts#L154):

// webpack v5
// compilation.hooks.processAssets.tap(
//  {
//     name: 'LicenseWebpackPlugin',
//     stage: WebpackCompilerHandler.PROCESS_ASSETS_STAGE_ADDITIONS
//   },
//   () => {
    this.assetManager.writeChunkBanners(
      this.moduleCache.getAllModulesForChunk(chunk.name),
      compilation,
      chunk
     );
//   }
//  );
xz64 commented 3 years ago

It looks like it is an ordering issue. The code which adds a hook to PROCESS_ASSETS_STAGE_ADDITIONS is called inside a hook to PROCESS_ASSETS_STAGE_REPORT. However, PROCESS_ASSETS_STAGE_ADDITIONS is supposed to occur before PROCESS_ASSETS_STAGE_REPORT. That's one part of the problem.

Another problem is that TerserPlugin (which is used automatically in production mode in webpack 5) moves the banner to the main.js.LICENSE.txt file. I will update the documentation showing how to turn off TerserPlugin's comment handling so that LicenseWebpackPlugin behaves the same way it did in webpack v4.

xz64 commented 3 years ago

Fixed in v2.3.19, but it will require some changes to your webpack configuration. See https://github.com/xz64/license-webpack-plugin/blob/master/DOCUMENTATION.md under the renderBanner section for the type of changes that are needed