Giter Site home page Giter Site logo

webpack-license-plugin's Introduction



webpack-license-plugin

Manage third-party license compliance in your webpack build

Continuous integration status Code coverage License: MIT Contact on Twitter

Key FeaturesInstallationHow to useAvailable optionsExamples

Key features

This plugin extracts open source license information about all of the npm packages in your webpack output and helps you identify and fix problems with your open source licensing policy.

This plugin has full unit and end to end test coverage and is tested with webpack 2, 3, 4 and 5. It will help you:

  • Discover every npm package used in your webpack output
  • Find out how it is licensed
  • Cancel builds that include unacceptable licenses
  • Exclude internal packages from being scanned
  • Create a customized inventory (usually called bill of materials) in json, html, csv or other formats

Installation

Install webpack-license-plugin as a development dependency to your current project

npm

$ npm install -D webpack-license-plugin

Yarn

$ yarn add -D webpack-license-plugin

How to use

Use webpack-license-plugin in your webpack configuration by adding it to the plugins array.

const LicensePlugin = require('webpack-license-plugin')

module.exports = {
  plugins: [
    // there might be other plugins here
    new LicensePlugin()
  ],
}

Available options

Options are given as an Object to the first parameter of the LicensePlugin constructor:

new LicensePlugin({ outputFilename: 'thirdPartyNotice.json' })

The available options are:

Name Description
additionalFiles Default: {}. Object that defines additional files that should be generated by this plugin based on it's default output (e.g. an html representation of the licenses in addition to the generated json). Keys represent filenames, values are functions that get invoked with the packages array and should return the content written to the additional file. These functions can be async or return a Promise.
excludedPackageTest A method to exclude packages from the process. It is invoked with packageName (string) and version (string) of every package and should return true to exclude the package.
licenseOverrides Default: {}. Object with licenses to override. Keys have the format <name>@<version>, values are valid spdx license expressions. This can be helpful when license information is inconclusive and has been manually checked.
outputFilename Default: oss-licenses.json. Path to the output file that will be generated. Relative to the bundle output directory.
replenishDefaultLicenseTexts Default: false. When this is enabled, default license texts are taken from spdx.org for packages where no license text was found.
unacceptableLicenseTest A method to define license identifiers as unacceptable. It is invoked with licenseIdentifier (string) for every package and should return true when the license is unacceptable and encountering it should fail the build.
includePackages Default: () => []. A method to define packages that should always be included in the output. It must return an array containing the absolute paths of those packages. This function can be async or return a Promise.

Example with custom options

This example writes the result to a file named meta/licenses.json in the output directory, fails whenever it encounters one of the given licenses and overrides the license of the package [email protected].

const LicensePlugin = require('webpack-license-plugin')

module.exports = {
  // ...
  plugins: [
    new LicensePlugin({
      excludedPackageTest: (packageName, version) => {
        return packageName.startsWith('@internal/')
      },
      licenseOverrides: {
        // has "Apache" in package.json, but Apache-2.0 text in LICENSE file
        '[email protected]': 'Apache-2.0'
      },
      outputFilename: 'meta/licenses.json',
      unacceptableLicenseTest: (licenseIdentifier) => {
        return ['GPL', 'AGPL', 'LGPL', 'NGPL'].includes(licenseIdentifier)
      }
    }),
  ],
}

Default output

The output is a oss-licenses.json file in the webpack build output directory. It contains an array of packages that were found to be part of the webpack output and lists several license-related details for every package:

Name Description
name package name
version package version
author author listed in package.json (if available)
repository repository url listed in package.json (if available)
source package tarball url on npm registry
license the license listed in package.json. If this is not a valid spdx license expression, this plugin will inform you. You can then inform the package maintainers about this problem and temporarily workaround this issue with the licenseOverrides option for the specific combination of package name and version.
licenseText the license text read from a file matching /^licen[cs]e/i in the package's root

Example output file

[
  {
    "name": "fbjs",
    "version": "0.8.17",
    "repository": "https://github.com/facebook/fbjs",
    "source": "https://registry.npmjs.org/fbjs/-/fbjs-0.8.17.tgz",
    "license": "MIT",
    "licenseText": "..."
  },
  {
    "name": "object-assign",
    "version": "4.1.1",
    "author": "Sindre Sorhus",
    "repository": "https://github.com/sindresorhus/object-assign",
    "source": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
    "license": "MIT",
    "licenseText": "..."
  },
  {
    "name": "react-dom",
    "version": "16.4.2",
    "repository": "https://github.com/facebook/react",
    "source": "https://registry.npmjs.org/react-dom/-/react-dom-16.4.2.tgz",
    "license": "MIT",
    "licenseText": "..."
  },
  {
    "name": "react",
    "version": "16.4.2",
    "repository": "https://github.com/facebook/react",
    "source": "https://registry.npmjs.org/react/-/react-16.4.2.tgz",
    "license": "MIT",
    "licenseText": "..."
  }
]

Examples

additionalFiles examples

When the additionalFiles option is set, the output shown above is passed into the transform function as an array for every additional file configured.

This way, the output can be formatted to any format you might need and then be written to one or more additional files.

Package list as CSV

const LicensePlugin = require('webpack-license-plugin')

function csvTransform(packages) {
  const keys = ['name', 'version', 'license']

  return [
    '"sep=,"',
    keys.join(','),
    ...packages.map(pckg => keys.map(key => `="${pckg[key]}"`).join(',')),
  ].join('\n')
}

module.exports = {
  // ...
  plugins: [
    new LicensePlugin({
      additionalFiles: {
        'oss-licenses.csv': csvTransform
      }
    }),
  ],
}

Package list and additional summary

const LicensePlugin = require('webpack-license-plugin')

module.exports = {
  // ...
  plugins: [
    new LicensePlugin({
      additionalFiles: {
        'oss-summary.json': packages => {
          return JSON.stringify(
            packages.reduce(
              (prev, { license }) => ({
                ...prev,
                [license]: prev[license] ? prev[license] + 1 : 1,
              }),
              {}
            ),
            null,
            2
          )
        },
      },
    }),
  ],
}

webpack-license-plugin's People

Contributors

codepunkt avatar dependabot-preview[bot] avatar dependabot-support avatar dependabot[bot] avatar fedjaw avatar greenkeeper[bot] avatar sebaspf avatar snyk-bot avatar toastal avatar wistudent avatar zoltan-mihalyi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

webpack-license-plugin's Issues

Passing 2nd package.json/project

Hi,

Just wondering if it is possible to include a whole 2nd project/package.json file in the output as well?

The expected bevhaviour for me would be like if you ran the plugin in both the current project + the other project you want, and merged + deduplicated the output file.

I see the includePackages option but doesn't seem like that accepts a whole project right?

EDIT: I think I misunderstood how this works, and it will probably be very difficult to do this as you'd actually need to hook into the 2nd project as well. I'll just do that and serve both files separately I think.

License file will not be generated(Conflict: Multiple assets emit different content to the same filename)

I test all sample usage that mentioned in README file in my Angular Project and all of them has this Error:

Error: Conflict: Multiple assets emit different content to the same filename meta/3dParty-Licenses.json

node v14.16.1
npm 6.14.13
webpack 5.44.0
angular/cli 12.1.4

Reproduction:

ng new sampleProject
npm i -D @angular-builders/custom-webpack
npm i -D webpack-license-plugin

Change angular build architect in angular.json file to:
"architect": { "build": { "builder": "@angular-builders/custom-webpack:browser", "options": { "customWebpackConfig": { "path": "./custom-webpack.config.js" }, ... }, }, }

Add this plugin into custom-webpack.config.js file.

ng build

CRA build with craco warns about multiple assets emitting to oss-licenses.json

In my case, I configure a create-react-app to use webpack-license-plugin via craco.

Reproduction repository (git archive): git-repro.zip Edit: See correct zip archive in comments.

Running yarn build produces the following warning:

Conflict: Multiple assets emit different content to the same filename oss-licenses.json

Similar to #491 and #435.

The current release of react-scripts (4.0.3) uses [email protected].

Reverting to [email protected] (which was before #510) does not resolve the issue.

Handling inconsistency between package.json and license text

Has any thought been given to checking whether the found license text correctly corresponds to what's in the package.json? It seems like a package could easily include a license but accidentally keep the default ISC in the package.json.

I've never seen a JavaScript implementation of this but the Licensee ruby gem (licenseejs is different) can detect license information from text. https://github.com/licensee/licensee

I'm thinking of implementing something myself to validate this but it seems like it could make sense for this functionality to be included in the plugin. That said it could take a long time to run so it would be something you would turn on with a special option.

allow excluding modules from result list

I'm working on a project where we are using multiple in-house modules which do not have a license (less so an SPDX license), which currently prevents me from using this otherwise great plugin. It would be nice to be able to exclude modules from the license check/aggregation.

I think this could be married with the "licenseOverrides" map by using a special "ignore" string as license, e.g.:

"licenseOverrides": {
   "@some-company/[email protected]": "ignore",
}

Handle packages with nested package.json

Some npm packages are structured with a nested package.json that only contains basic info without the license, but the root package.json has the license info.

For example, socket.io-client:

├── build/esm/package.json
└── package.json

The root package.json looks like this:

{
  "name": "socket.io-client",
  "version": "4.4.0",
  "main": "./build/cjs/index.js",
  "module": "./build/esm/index.js",
  "license": "MIT",

And the nested package.json looks like this:

{
  "name": "socket.io-client",
  "version": "4.4.0",
  "type": "module"
}

This plugin currently picks up the nested package.json, which doesn't contain any license info, causing the error "Could not find license info for [email protected]".

Would it make sense for ModuleDirectoryLocator to check the parent directory in case the package license and licenses properties are both undefined? I'd be happy to try my hand at a pull request if you agree this makes sense. Thanks!

Also NOTICE text should be included in the output

Hi,

I'd like to use this plugin to comply with a bunch libraries licenses that I include in my webapp bundle. But I noticed that the NOTICE file text is not included in the output although, from what I understand, it is a requirement of some licenses such as Apache 2.0.

https://www.apache.org/licenses/LICENSE-2.0.txt 4.d

If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.

Do you think this feature could be added? I could also work on it and open a PR (I've never worked on a webpack plugin, but I can give it a try)

Output includes licenses of devDependencies

This may just be my limited understanding, but my output json file includes licenses for webpack amongst other things. I do not depend on webpack directly but a build tool in devDependencies depends on webpack.

Is this expected behaviour? I would have thought licenses of dev dependencies would not need to be included since I'm not re-distributing them in any bundles etc.

An in-range update of react is breaking the build 🚨

There have been updates to the react monorepo:

    • The devDependency react-dom was updated from 16.6.1 to 16.6.2.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

This monorepo update includes releases of one or more dependencies which all belong to the react group definition.

react is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ci/circleci: Your tests failed on CircleCI (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Can not return a promise from `additionalFiles` functions

At the moment you can not return a promise from functions attached to additionalFiles. The code does actually use await internally but the validator incorrectly passes an empty array in and asserts that the result is a string where it should also be allowed to be a promise that returns a string.

Investigate DeprecationWarnings

(node:131) DeprecationWarning: Chunk.modulesIterable: Use new ChunkGraph API
(node:131) DeprecationWarning: Chunk.entryModule: Use new ChunkGraph API

Probably webpack 5 related.

Parsing the license data from LICENSE not working

Hi,

first of all, thank you very much for this great plugin. I've tried a lot of webpack/npm license tools and this one is my favorite one so far.

From the README:

the license listed in package.json. If it's not available or not a valid spdx license expression, additional files such as LICENSE or README are being looked at in order to parse the license data from them. (this will be shown with a * next to the name of the license and may require further manual verification)

Looks like this isn't working as expected.

Here is an example where the spdx short identifier for the license in package.json is not correct (a "-" is missing) but in the LICENSE file the license is mentioned (BSD 2-Clause):

https://spdx.org/licenses/BSD-2-Clause.html

@mapbox/[email protected]
https://github.com/mapbox/fusspot/blob/0.4.0/package.json#L25
https://github.com/mapbox/fusspot/blob/0.4.0/LICENSE

The build fails with the following error:

ERROR in WebpackLicensePlugin: License "BSD 2-Clause" for @mapbox/[email protected] is not a valid SPDX expression!

Maybe the parsing of the LICENSE fails because there is only BSD 2-Clause license in there and not the spdx short identifier?

All in all, this is not a big deal because it's possible to use the licenseOverrides option:

      licenseOverrides: {
        '@mapbox/[email protected]': 'BSD-2-Clause'
      }

The package being build is not included in the output.

When building the code for redistributing (e.g. a frontend or a module), the dependencies and also the current package information must be included in the output file. As the final bundle includes both, the dependencies and the new code, all licences must be present.

Steps to reproduce:

# From the repository root
cd test/e2e/example 
node ../../../node_modules/webpack/bin/webpack.js --config ../webpack.config.js

check that test/e2e/example/dist/oss-licences.json does not contain the example package (webpack-license-plugin-test-example)

Handle custom license with no valid SPDX identifier

According #443 (comment)

As of now, this plugin requires valid SPDX identifiers in the license field and checks for the license text in a licen[cs]e file.

There are use cases where there is no valid SPDX identifiers in package.json but something like SEE LICENSE IN LICENSE.txt.

Here is an example (which was also valid before the recent license change when BSD-3-Clause used to be the license):

https://github.com/mapbox/mapbox-gl-js/blob/20b953937ac54e3743aed06066b0bbe0092f5c9a/package.json#L7

What about a licenseOverrides option:

"license": "see licenseText"

which takes the license text of a licen[cs]e file for licenseText?

Collecting licenses for monorepo packages when license is only in root level

Hi,
we are using 'swr' package and lately we upgraded to the latest version (1.3.0) and got a new error during the build:

WebpackLicensePlugin: Could not find license info for [email protected]

It seems the repo changed to a mono-repo causing an issue to collect the license for the sub-packages (since he only exists at the root level).

Are you going to detect cases like that or expect each package to have a license?

`outputWriter` option

Looking to replace this plugin, which has an option outputWriter to pass a function that performs the output formatting. It could work like this:

new LicensePlugin({
  outputFilename: 'licenses.txt',
  outputWriter: deps => deps.map(dep => dep.name).join('\n'),
});

I could contribute this feature if it's accepted.

How to use with next.js?

I tried following next.config.js

const LicensePlugin = require('webpack-license-plugin');

const nextConfig = {
  // If you change the basePaths, also change path for favicon in _document.js
  basePath: '/mica-tool-wGlobal/python/front_end/out',
  reactStrictMode: true,
  images: {
    unoptimized: true // required for static export to work
  },
  webpack: (config) => {
    config.resolve.fallback = {
      'fs': false
    };

    config.plugins = [new LicensePlugin()]

    return config;
  }

};

// eslint-disable-next-line unicorn/prefer-module
module.exports = nextConfig;

and got

npm run build

> [email protected] build
> next build && next export

- info Linting and checking validity of types  
- info Disabled SWC as replacement for Babel because of custom Babel configuration "babel.config.json" https://nextjs.org/docs/messages/swc-disabled
(node:17744) [DEP_WEBPACK_COMPILATION_OPTIMIZE_CHUNK_ASSETS] DeprecationWarning: optimizeChunkAssets is deprecated (use Compilation.hooks.processAssets instead and use one of Compilation.PROCESS_ASSETS_STAGE_* as stage option)
(Use `node --trace-deprecation ...` to show where the warning was created)
Failed to compile.

./node_modules/next/dist/pages/_app.js
TypeError: Cannot read properties of undefined (reading 'traceChild')
    at Object.nextBabelLoaderOuter (C:\python_env\workspace\micat\front_end\node_modules\next\dist\build\babel\loader\index.js:31:46)

./node_modules/next/dist/pages/_document.js
TypeError: Cannot read properties of undefined (reading 'traceChild')
    at Object.nextBabelLoaderOuter (C:\python_env\workspace\micat\front_end\node_modules\next\dist\build\babel\loader\index.js:31:46)

./node_modules/next/dist/pages/_error.js
TypeError: Cannot read properties of undefined (reading 'traceChild')
    at Object.nextBabelLoaderOuter (C:\python_env\workspace\micat\front_end\node_modules\next\dist\build\babel\loader\index.js:31:46)

Import trace for requested module:
./node_modules/next/dist/pages/_error.js

./src/pages/[id-mode]/[id-region]/index.js
TypeError: Cannot read properties of undefined (reading 'traceChild')
    at Object.nextBabelLoaderOuter (C:\python_env\workspace\micat\front_end\node_modules\next\dist\build\babel\loader\index.js:31:46)

Import trace for requested module:
./src/pages/[id-mode]/[id-region]/index.js

HookWebpackError: Cannot read properties of undefined (reading 'traceChild')
    at makeWebpackError (C:\python_env\workspace\micat\front_end\node_modules\next\dist\compiled\webpack\bundle5.js:28:311139)
    at C:\python_env\workspace\micat\front_end\node_modules\next\dist\compiled\webpack\bundle5.js:28:105980
    at eval (eval at create (C:\python_env\workspace\micat\front_end\node_modules\next\dist\compiled\webpack\bundle5.js:13:28867), <anonymous>:58:1)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
-- inner error --
TypeError: Cannot read properties of undefined (reading 'traceChild')
    at TerserPlugin.optimize (C:\python_env\workspace\micat\front_end\node_modules\next\dist\build\webpack\plugins\terser-webpack-plugin\src\index.js:92:44)
    at C:\python_env\workspace\micat\front_end\node_modules\next\dist\build\webpack\plugins\terser-webpack-plugin\src\index.js:259:31
    at fn (C:\python_env\workspace\micat\front_end\node_modules\next\dist\compiled\webpack\bundle5.js:28:69698)
    at _next0 (eval at create (C:\python_env\workspace\micat\front_end\node_modules\next\dist\compiled\webpack\bundle5.js:13:28867), <anonymous>:50:17)
    at eval (eval at create (C:\python_env\workspace\micat\front_end\node_modules\next\dist\compiled\webpack\bundle5.js:13:28867), <anonymous>:66:1)
    at eval (eval at create (C:\python_env\workspace\micat\front_end\node_modules\next\dist\compiled\webpack\bundle5.js:13:28867), <anonymous>:11:1)
    at C:\python_env\workspace\micat\front_end\node_modules\next\dist\compiled\webpack\bundle5.js:28:69336
    at Hook.eval [as callAsync] (eval at create (C:\python_env\workspace\micat\front_end\node_modules\next\dist\compiled\webpack\bundle5.js:13:28867), <anonymous>:7:1)
    at Hook.CALL_ASYNC_DELEGATE [as _callAsync] (C:\python_env\workspace\micat\front_end\node_modules\next\dist\compiled\webpack\bundle5.js:13:26021)
    at C:\python_env\workspace\micat\front_end\node_modules\next\dist\compiled\webpack\bundle5.js:28:69505
caused by plugins in Compilation.hooks.processAssets
TypeError: Cannot read properties of undefined (reading 'traceChild')
    at TerserPlugin.optimize (C:\python_env\workspace\micat\front_end\node_modules\next\dist\build\webpack\plugins\terser-webpack-plugin\src\index.js:92:44)
    at C:\python_env\workspace\micat\front_end\node_modules\next\dist\build\webpack\plugins\terser-webpack-plugin\src\index.js:259:31
    at fn (C:\python_env\workspace\micat\front_end\node_modules\next\dist\compiled\webpack\bundle5.js:28:69698)
    at _next0 (eval at create (C:\python_env\workspace\micat\front_end\node_modules\next\dist\compiled\webpack\bundle5.js:13:28867), <anonymous>:50:17)
    at eval (eval at create (C:\python_env\workspace\micat\front_end\node_modules\next\dist\compiled\webpack\bundle5.js:13:28867), <anonymous>:66:1)
    at eval (eval at create (C:\python_env\workspace\micat\front_end\node_modules\next\dist\compiled\webpack\bundle5.js:13:28867), <anonymous>:11:1)
    at C:\python_env\workspace\micat\front_end\node_modules\next\dist\compiled\webpack\bundle5.js:28:69336
    at Hook.eval [as callAsync] (eval at create (C:\python_env\workspace\micat\front_end\node_modules\next\dist\compiled\webpack\bundle5.js:13:28867), <anonymous>:7:1)
    at Hook.CALL_ASYNC_DELEGATE [as _callAsync] (C:\python_env\workspace\micat\front_end\node_modules\next\dist\compiled\webpack\bundle5.js:13:26021)
    at C:\python_env\workspace\micat\front_end\node_modules\next\dist\compiled\webpack\bundle5.js:28:69505


> Build failed because of webpack errors
- info Creating an optimized production build .

Without the extra plugin entry npm run build works fine.

Enhancement: Add "includePackages" option

I am creating a hybrid android/ios app using capacitor. The web part is built with webpack and uses webpack-license-plugin. But because of capacitor's structure, some dependencies like @capacitor/android are not imported in the web part, but used by the native wrapper around it. Because they are not imported in the web part, webpack-license-plugin cannot see these dependencies.

As a workaround I am using the following code to collect the licenses for a predefined list of packages:

import LicenseMetaAggregator from 'webpack-license-plugin/dist/LicenseMetaAggregator';
import WebpackFileSystem from 'webpack-license-plugin/dist/WebpackFileSystem';
import fs from 'fs';
import PackageJsonReader from 'webpack-license-plugin/dist/PackageJsonReader';
import path from 'path';
import unacceptableLicenseTest from './unacceptableLicenseTest';

export const additionalPackages = async () => {
  const fileSystem = new WebpackFileSystem(fs);
  const alertAggregator = {
    addError: (message: string) => {
      throw new Error(message);
    },
    addWarning: () => {},
    flushAlerts: () => {}
  };
  const options = {
    additionalFiles: {},
    licenseOverrides: {},
    outputFilename: '',
    replenishDefaultLicenseTexts: true,
    unacceptableLicenseTest,
    excludedPackageTest: () => false
  };
  const licenseMetaAggregator = new LicenseMetaAggregator(fileSystem, alertAggregator, options, new PackageJsonReader(fileSystem));
  const modules = ['@capacitor/android', '@capacitor/ios'].map(m => path.dirname(require.resolve(`${m}/package.json`)));
  return await licenseMetaAggregator.aggregateMeta(modules);
};

The packages retuned by this function are then merged with the packages from webpack-license-plugin using the additionalFiles option:

new LicensePlugin({
  additionalFiles: {
    'oss-licenses.json': async (packages) => {
      return JSON.stringify([...packages, ...(await additionalPackages())]);
    }
  }.
  replenishDefaultLicenseTexts: true,
  unacceptableLicenseTest
})

This works fine (it extracts the licenses correctly and throws errors for unacceptable licenses), but except for the moduleDirs source it is basicly the same code as inside the webpack-license-plugin. Therefore I would like to propose an additional option includePackages that allows to define a list of packages whose licenses should always be included in the license output.

Remove outputTransform option

Transforms can be added via additionalFiles - it might be better in the long run if the json standard format is always produced - e.g. for debuggability of user problems

DeprecationWarning: optimizeChunkAssets is deprecated

I get a deprecation warning which looks like it is caused by webpack-license-plugin:

(node:16600) [DEP_WEBPACK_COMPILATION_OPTIMIZE_CHUNK_ASSETS] DeprecationWarning: optimizeChunkAssets is deprecated (use Compilation.hooks.processAssets instead and use one of Compilation.PROCESS_ASSETS_STAGE_* as stage option)
    at WebpackLicensePlugin.handleCompilation ([...]\node_modules\webpack-license-plugin\src\WebpackLicensePlugin.ts:70:45)
    at Hook.eval (eval at create ([...]\node_modules\tapable\lib\HookCodeFactory.js:19:10), <anonymous>:100:1)
    at Hook.CALL_DELEGATE [as _call] ([...]\node_modules\tapable\lib\Hook.js:14:14)
    at Compiler.newCompilation ([...]\node_modules\webpack\lib\Compiler.js:1126:26)
    at [...]\node_modules\webpack\lib\Compiler.js:1170:29
    at Hook.eval [as callAsync] (eval at create ([...]\node_modules\tapable\lib\HookCodeFactory.js:33:10), <anonymous>:6:1)
    at Hook.CALL_ASYNC_DELEGATE [as _callAsync] ([...]\node_modules\tapable\lib\Hook.js:18:14)
    at Compiler.compile ([...]\node_modules\webpack\lib\Compiler.js:1165:28)
    at [...]\node_modules\webpack\lib\Compiler.js:524:12
    at Compiler.readRecords ([...]\node_modules\webpack\lib\Compiler.js:989:5)

Plugin is used without options:

{
  ... 
  plugins: [new HtmlWebpackPlugin(), new LicensePlugin()],
}

Versions

All up to date.

webpack: 5.88.2
webpack-license-plugin: 4.2.2

webpack 5 support

Hello! Thanks for a great plugin!

We're getting errors using webpack 5.

Conflict: Multiple assets emit different content to the same filename oss-licenses.json.

I can create a repro repo but don't have time for that right now.

Build fails with unclear error message: "Error"

I can't point to an actual Github repo / app (private repo) but you should be able to reproduce by doing the following:

Actual behavior: The plugin errors out (expected) but the message shown is the very unclear string Error
Desired behavior: The error message is formatted properly: License "BSD 2-Clause" for @mapbox/[email protected] is not a valid SPDX expression!

I figured out the error message that wasn't being shown properly by going into into node_modules and add a console.log(message); here:

this.errors.push(message)

I'm investigating further to try to figure out why this happened - wondering if there's something going wrong between and when an error in this particular format is in the array.

License "UNLICENSED" is not a valid SPDX expression!

ERROR in WebpackLicensePlugin: License "UNLICENSED" is not a valid SPDX expression!

I have several proprietary / private packages on npm. I have denoted them as licence: "UNLICENSED" in package.json, as from what I understand that would be the right term.

But why is this throwing an error then?

Manually include a license

Is there a way to hard-code a license so that it always shows up? For example, with copied code that is not in a separate package.

Additional output fields from `package.json`

Would it be possible to allow the consumer to define additional fields that they would like extracted from package.json and added into the output JSON? For instance, I'm looking to get the homepage field. I think with a simple addition to the options and reflection in the LicenseMetaAggregator this can be accomplished.

I can also help with the implementation and PR if you'd prefer.

TypeError with Webpack 5

I'm running into an error while using it with Webpack 5.75.0:

\ Generating browser application bundles (phase: setup)...WebpackLicensePlugin.ts:70
      compilation.hooks.optimizeChunkAssets.tapAsync(
                                            ^
TypeError: Cannot read properties of undefined (reading 'tapAsync')
    at WebpackLicensePlugin.handleCompilation (WebpackLicensePlugin.ts:70:45)<anonymous>:31:1)

I think this is fixed by your commits since the latest release. I tried downloading the source code and building the plugin, and then everything worked as expected.

Can you publish a new version to fix this?

Thanks for the great plugin :)

Get rid of duplicate package@version in output

The module directories are currently being deduplicated - however, a package in a certain version can be nested in different module directories.

for example:

These will lead to the same license information in the output, which is why it should be de-duplicated on a package@version level aswell.

ESM build does not work in ES module config files

I tried using the published ESM build in a Webpack project, but encountered errors directly upon importing the plugin using:

import LicensePlugin from 'webpack-license-plugin';

The error in question:

SyntaxError: Named export 'WebpackError' not found. The requested module 'webpack' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:

Digging some more into it, there seems to be two issues with the current ESM bundle preventing it from being used in an ES Module webpack config file:

  1. There are named imports from CommonJS modules, which aren't always supported by Node as the error message also indicates. TypeScript allows this just fine, hence it not causing issues when building. See microsoft/TypeScript#54018
  2. The bundle contains a CommonJS specific footer (added here), which isn't valid in an ES module.

Upgrade from 4.2.2 to 4.2.3 / 4.3.0 => TypeError: WebpackLicensePlugin is not a constructor

Hi,

I use WebpackLicensePlugin on my project for a few years. Today I simply upgraded the webpack-license-plugin in my package.json (from 4.2.2 to 4.3.0) and I systematically get an error when running webpack : TypeError: WebpackLicensePlugin is not a constructor.

Note : I also tried 4.2.3 and I got the same result.

To isolate the problem, I've emptied my webpack configuration file so that it only contains the following code (not a valid webpack configuration file, but it's not a problem as we only want to isolate and reproduce the raising error) :

const WebpackLicensePlugin = require('webpack-license-plugin');
console.error('** Before new WebpackLicensePlugin');
const plugin = new WebpackLicensePlugin();
console.error('** After new WebpackLicensePlugin');

The result :

Running webpack (webpack.prod.js)...
** Before new WebpackLicensePlugin
[webpack-cli] Failed to load '[hidden]/webpack.prod.js' config
[webpack-cli] TypeError: WebpackLicensePlugin is not a constructor
    at Object.<anonymous> ([hidden]/webpack.prod.js:3:16)
    at Module._compile (node:internal/modules/cjs/loader:1159:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1213:10)
    at Module.load (node:internal/modules/cjs/loader:1037:32)
    at Module._load (node:internal/modules/cjs/loader:878:12)
    at Module.require (node:internal/modules/cjs/loader:1061:19)
    at require (node:internal/modules/cjs/helpers:103:18)
    at WebpackCLI.tryRequireThenImport ([hidden]/node_modules/webpack-cli/lib/webpack-cli.js:223:30)
    at loadConfigByPath ([hidden]/node_modules/webpack-cli/lib/webpack-cli.js:1406:38)
    at [hidden]/node_modules/webpack-cli/lib/webpack-cli.js:1460:88
error Command failed with exit code 2.

I use webpack 5 :

    "webpack": "^5.88.2",
    "webpack-cli": "^5.1.4",
    "webpack-dev-server": "^4.15.1",
    "webpack-license-plugin": "^4.2.3",

I understand that I probably make a very basic mistake, but I must admit that I don't understand what (I checked the documentation and the installation section does not seem to have changed since 4.2.2).

Thank you in advance for your return.

Packages with no SPDX licence cause a build to fail

Enhancement

When building using dependencies with no SPDX license, the complete build fails as the check in this line fails generating an error. This behavior may be sometimes a problem when using many of these packages or when a different team handles the build configs. A possible solution could be to exclude them, but it requires an intervention for every new dependency.

Anew option handleNonSPDX with the flowing values would be very handy for many applications:

  • reject: default, current behavior
  • ignore: do not list these packages in the output
  • warning: Add them to the output and show a warning.

Some dependencies are missing with no error/warning

Please have a look at this repo to reproduce the issue.

In the example above date-fns is imported, it is part of the build but the oss-licenses.json is empty.

I found a few dependencies in some of my projects that are also missing:

  • @popperjs/core (2.4.4)
  • deepmerge (2.1.1)
  • dom-helpers (5.0.1)
  • formik (2.2.9)
  • history (4.10.0)
  • loadash-es (4.17.11)
  • mini-create-react-context (0.4.1)
  • react-router (5.2.1)
  • react-router-dom (5.2.1)
  • react-transition-group (4.4.2)
  • resolve-pathname (3.0.0)
  • single-spa-react (3.2.0)
  • stylis (4.0.3)
  • symbol-observable (4.0.0)
  • tiny-invariant (1.0.2)
  • tiny-warning (1.0.2)
  • uuid (3.3.2)
  • value-equal (1.0.1)

Webpack Deprecation Warning during build proccess

After using this plugin in build process this warning will be appeared on output:

(node:21144) [DEP_WEBPACK_COMPILATION_OPTIMIZE_CHUNK_ASSETS] DeprecationWarning: optimizeChunkAssets is deprecated (use Compilation.hooks.processAssets instead and use one of Compilation.PROCESS_ASSETS_STAGE_* as stage option)
(Use node --trace-deprecation ... to show where the warning was created)

node v14.16.1
npm 6.14.13
webpack 5.44.0
angular/cli 12.1.4

Clarify selection

This is mostly a documentation question.

I noticed that webpack-license-plugin results in quite a few less "items" than license-checker, even when I filter license-checker on just production and just direct dependencies.
I do clearly see that at least all the import's I'm doing in my code are included by webpack-license-plugin. I even find dependencies of those imports.
I'm assuming license-checker does not do tree shaking, so that might explain a lot.
Update: license-checker's direct option doesn't work
I'm not asking to explain the differences, but a bit more info on how the selection works would be very interesting. Is it really as simple as what's gets included in the build, and thus gets distributed, gets included in the list?

I'm hoping to get some legal advice soon, but shouldn't code that's used to create the project, but isn't distributed, also be included? Things like eslint, webpack loaders, in my case vue-cli relates packages?

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software

But maybe the idea is that we're not copying things like eslint / webpack loaders etc even though we are using it locally.

webpack-license-plugin:

  • MIT: 65
  • BSD-3-Clause: 7
  • ISC: 3
  • Apache-2.0: 1
  • 0BSD: 1

license-checker:

$ npx license-checker  --summary --production --excludePrivatePackages 
├─ MIT: 251
├─ ISC: 31
├─ BSD-2-Clause: 16
├─ BSD-3-Clause: 12
├─ Apache-2.0: 4
├─ CC0-1.0: 2
├─ 0BSD: 2
├─ (MIT OR CC0-1.0): 2
└─ MIT*: 1

$ npx license-checker --summary --production --excludePrivatePackages --direct
├─ MIT: 290
├─ ISC: 24
├─ BSD-2-Clause: 14
├─ BSD-3-Clause: 12
├─ Apache-2.0: 4
├─ (MIT OR Apache-2.0): 1
├─ BSD*: 1
├─ CC0-1.0: 1
├─ 0BSD: 1
├─ (MIT OR CC0-1.0): 1
└─ MIT*: 1

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.