Coder Social home page Coder Social logo

waysact / webpack-subresource-integrity Goto Github PK

View Code? Open in Web Editor NEW
355.0 14.0 46.0 4.1 MB

Webpack plugin for enabling Subresource Integrity.

License: MIT License

Emacs Lisp 0.13% JavaScript 10.50% TypeScript 89.37%
webpack sri html-webpack-plugin subresource-integrity

webpack-subresource-integrity's Introduction

webpack-subresource-integrity

npm version Build Status Coverage Status License

If you're looking for installation and usage instructions, visit the main package.

Or you might be looking for the 1.x version with support for Webpack 1-4 and older versions of html-webpack-plugin? Visit the 1.x branch.

Upgrading from version 1.x? Read the migration guide.

If you want to hack on the package, read on โ€” you're in the right place.

Installing from source

To install from source, clone this repository, cd into it and run

yarn

Note: this repository uses yarn workspaces; you have to use a recent version of Yarn, npm won't work. (This limitation does not apply to the built package; you can install that with npm, yarn, or any other package manager.)

Running tests

The following will run all unit tests, integration tests, examples, and lint. It will also build the package and run a smoke test on the resulting tarball:

yarn check

Adding a new test

The easiest way to add a new test is to create an example, which is an integration test. An example is a self-contained package in directory example. It should follow these simple rules:

  • When yarn webpack is invoked inside the package, it returns a zero exit code for a test pass, and a non-zero exit code for a test failure.
  • The package must have nyc installed for coverage reporting to work.
  • The package must specify * as the version for webpack-subresource-integrity so that it picks up the version from inside the workspace (instead of using a published version.)
  • The package should use expect for testing expectations.
  • The package should make sure all versions it uses for nyc, expect, webpack etc. match those used in other examples, unless there's a good reason to use a different version.
  • If the example is an end-to-end test (runs tests in the browser) it should use wsi-test-helper to do so. See its README for more information.

webpack-subresource-integrity's People

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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

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

webpack-subresource-integrity's Issues

ng build --prod ERROR in Cannot assign to a reference or variable!

Hello,

Here is the error message I get after a ng build --prod on Angular app. Could you help me to resolve this problem please ?

ERROR in Cannot assign to a reference or variable!
Child mini-css-extract-plugin node_modules/@angular-devkit/build-angular/src/angular-cli-files/plugins/raw-css-loader.js!node_modules/postcss-loader/src/index.js??extracted!node_modules/@angular/material/prebuilt-themes/indigo-pink.css:
                   Asset      Size  Chunks  Chunk Names
    3rdpartylicenses.txt  1.07 KiB
    Entrypoint mini-css-extract-plugin = *
    chunk    {0} * (mini-css-extract-plugin) 64.2 KiB [entry] [rendered]
     [Ysuc] ./node_modules/@angular-devkit/build-angular/src/angular-cli-files/plugins/raw-css-loader.js!./node_modules/postcss-loader/src??extracted!./node_modules/@angular/material/prebuilt-themes/indigo-pink.css 64.2 KiB {0} [built]
         ModuleConcatenation bailout: Module is not an ECMAScript module
         single entry !!c:\angular\test-nebular_1_19_0\node_modules\@angular-devkit\build-angular\src\angular-cli-files\plugins\raw-css-loader.js!c:\angular\test-nebular_1_19_0\node_modules\postcss-loader\src\index.js??extracted!c:\angular\test-nebular_1_19_0\node_modules\@angular\material\prebuilt-themes\indigo-pink.css  mini-css-extract-plugin
         factory:8ms building:343ms = 351ms
Child mini-css-extract-plugin node_modules/@angular-devkit/build-angular/src/angular-cli-files/plugins/raw-css-loader.js!node_modules/postcss-loader/src/index.js??extracted!node_modules/@nebular/theme/styles/prebuilt/default.css:
                   Asset      Size  Chunks  Chunk Names
    3rdpartylicenses.txt  2.14 KiB
    Entrypoint mini-css-extract-plugin = *
    chunk    {0} * (mini-css-extract-plugin) 146 KiB [entry] [rendered]
     [i5tx] ./node_modules/@angular-devkit/build-angular/src/angular-cli-files/plugins/raw-css-loader.js!./node_modules/postcss-loader/src??extracted!./node_modules/@nebular/theme/styles/prebuilt/default.css 146 KiB {0} [built]
         ModuleConcatenation bailout: Module is not an ECMAScript module
         single entry !!c:\angular\test-nebular_1_19_0\node_modules\@angular-devkit\build-angular\src\angular-cli-files\plugins\raw-css-loader.js!c:\angular\test-nebular_1_19_0\node_modules\postcss-loader\src\index.js??extracted!c:\angular\test-nebular_1_19_0\node_modules\@nebular\theme\styles\prebuilt\default.css  mini-css-extract-plugin
         factory:72ms building:286ms = 358ms
Child mini-css-extract-plugin node_modules/@angular-devkit/build-angular/src/angular-cli-files/plugins/raw-css-loader.js!node_modules/postcss-loader/src/index.js??extracted!node_modules/bootstrap/dist/css/bootstrap.min.css:
                   Asset      Size  Chunks  Chunk Names
    3rdpartylicenses.txt  3.26 KiB
    Entrypoint mini-css-extract-plugin = *
    chunk    {0} * (mini-css-extract-plugin) 153 KiB [entry] [rendered]
     [aogg] ./node_modules/@angular-devkit/build-angular/src/angular-cli-files/plugins/raw-css-loader.js!./node_modules/postcss-loader/src??extracted!./node_modules/bootstrap/dist/css/bootstrap.min.css 153 KiB {0} [built]
         ModuleConcatenation bailout: Module is not an ECMAScript module
         single entry !!c:\angular\test-nebular_1_19_0\node_modules\@angular-devkit\build-angular\src\angular-cli-files\plugins\raw-css-loader.js!c:\angular\test-nebular_1_19_0\node_modules\postcss-loader\src\index.js??extracted!c:\angular\test-nebular_1_19_0\node_modules\bootstrap\dist\css\bootstrap.min.css  mini-css-extract-plugin
         factory:74ms building:423ms = 497ms
Child mini-css-extract-plugin node_modules/@angular-devkit/build-angular/src/angular-cli-files/plugins/raw-css-loader.js!node_modules/postcss-loader/src/index.js??extracted!node_modules/sass-loader/lib/loader.js??ref--15-3!src/styles.scss:
                   Asset      Size  Chunks  Chunk Names
    3rdpartylicenses.txt  3.26 KiB
    Entrypoint mini-css-extract-plugin = *
    chunk    {0} * (mini-css-extract-plugin) 236 bytes [entry] [rendered]
     [/c4r] ./node_modules/@angular-devkit/build-angular/src/angular-cli-files/plugins/raw-css-loader.js!./node_modules/postcss-loader/src??extracted!./node_modules/sass-loader/lib/loader.js??ref--15-3!./src/styles.scss 236 bytes {0} [built]
         ModuleConcatenation bailout: Module is not an ECMAScript module
         single entry !!c:\angular\test-nebular_1_19_0\node_modules\@angular-devkit\build-angular\src\angular-cli-files\plugins\raw-css-loader.js!c:\angular\test-nebular_1_19_0\node_modules\postcss-loader\src\index.js??extracted!c:\angular\test-nebular_1_19_0\node_modules\sass-loader\lib\loader.js??ref--15-3!c:\angular\test-nebular_1_19_0\src\styles.scss  mini-css-extract-plugin
         factory:258ms building:45ms = 303ms

WARNING in Conflict: Multiple assets emit different content to the same filename 3rdpartylicenses.txt

WARNING in Conflict: Multiple assets emit different content to the same filename 3rdpartylicenses.txt

WARNING in Terser Plugin: Dropping unused variable sriHashes_1 [runtime-es2015.c13f31dd9f49759182a3.js:64,14]

WARNING in Terser Plugin: Dropping unused variable sriHashes_2 [runtime-es2015.c13f31dd9f49759182a3.js:64,14]

WARNING in Terser Plugin: Dropping unused variable sriHashes_3 [runtime-es2015.c13f31dd9f49759182a3.js:64,14]

WARNING in Terser Plugin: Dropping side-effect-free statement [scripts.4513c2c88dc8c3fd5569.js:2,66549]

WARNING in Terser Plugin: Dropping unreachable code [scripts.4513c2c88dc8c3fd5569.js:2,83630]

WARNING in Terser Plugin: Declarations in unreachable code! [scripts.4513c2c88dc8c3fd5569.js:2,83630]

WARNING in webpack-subresource-integrity: Cannot determine asset for chunk scripts, computed="undefined", available=scripts.4513c2c88dc8c3fd5569.js. Please report this full error message along with your Webpack configuration at https://github.com/waysact/webpack-subresource-integrity/issues/new

ERROR in Cannot assign to a reference or variable!

Deprecate crossorigin option

Webpack has an option output.crossOriginLoading used for loading chunks with code splitting. It's confusing that this plugin offers a similar option for use on asset tags generated by html-webpack-plugin. Starting with version 0.8.0, the webpack option is reused by default and the plugin option is deprecated.

To make code written for version 0.7.0 work without warnings in 0.8.0, ensure that the output.crossOriginLoading webpack option is set and that there is no crossorigin option in the plugin configuration.

Broken on Windows

We integrated this plugin into Create React App (facebook/create-react-app#1202), and the build breaks on Windows:

To reproduce:

npm i -g create-react-app
create-react-app myapp --scripts-version 0.8.2

cd myapp
npm run build

This happens on Windows because the generated compilation assets key contains Windows path separators but Webpack expected a normalized one.

SRI warning for ng build

WARNING in webpack-subresource-integrity: Cannot determine asset for chunk scripts, computed="undefined", available=scripts.c665f7f0f030771d6d1a.js.

Webpack Core Dependency

Hi,

I'm currently auditing our dependencies for projects missing a LICENCE file. This project has one but
depends on webpack-core which is missing a licence (it names the licence but this is not sufficient). The problem is the project has been archived and is no longer maintained so I can't even submit a MR to add the file.

Is this dependency still needed? or is there any plan to remove it? I guess even ignoring licencing it's not great to rely on unmaintained libraries.

Thanks.

Use with create-react-app?

I know there was [reverted] and still is an effort to get this officially working with create-react-app, but in the mean-time, what is the best workaround to get this working on the built version of the app that create-react-app generates?

Undocumented critical plugin order with Uglifier

This plugin appears to share one or more event hooks with the Uglifier plugin, and thus their plugin order is significant. The chunks SRI manifest (installed by WebIntegrityJsonpMainTemplatePlugin) is a noop when this plugin is ordered after Uglifier.

While the problem is solved easily enough, it would be helpful if this critical ordering concern was documented.

webpack-subresource-integrity overwrites integrity values on explicitly set externals

I'm using webpack-subresource-integrity to set integrity hashs on local resources. This works fine. At the same time I'm defining externals (including integrity hash) manually with html-webpack-externals-plugin like this:

    new HtmlWebpackExternalsPlugin({
      externals: [
        {
          module: 'jquery',
          entry: {
            path: 'https://code.jquery.com/jquery-3.2.1.js',
            attributes: {
              integrity: 'sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=',
              crossorigin: 'anonymous',
            },
          },
          global: 'jQuery',
        },
      ],
    })

However, the integrity attribute get's overwritten by webpack-subresource-integrity with null, resulitng in this:

<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.js" integrity="null" crossorigin="anonymous"></script>

Is there anyway to prevent this unwanted behavior?

webpack 4.5 error - Cannot read property 'publicPath' of undefined

Hi all,

In my custom webpack configuration i encounter some issues, regarding updating from webpack 3.x to 4.5 OR 4.4. Does anyone recognise the error or has any idea to get this fixed?

image

when i look at the code of this plugin i found the code is hitting over here:
image

This error may come from other packages, however if i disable the SRi rule, the webpack build will succeed

Thanx, regards
Bart Jan

Typescript typings

I am trying to create Typescript definition for this plugin in order to use Typescript for my webpack.config.

Would you be ok with distributing the package with Typescript definition? If not, I'll push the typings to DefinitelyTyped instead.

WARNING in webpack-subresource-integrity: your app told me to give a warning

WARNING in webpack-subresource-integrity: Cannot determine asset for chunk scripts, computed="undefined", available=scripts.js. Please report this full error message along with your Webpack configuration at https://github.com/waysact/webpack-subresource-integrity/issues/new,

I couldnt find a webpack.config.ts how ever heres a WebpackOptions.json I found

webpackOptions.txt
package.json.txt

my env
Software :Angular 9.1.11
OS: Windows 10 Home
Terminal:
PSVersion 5.1.17763.1007
PSEdition Desktop
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
BuildVersion 10.0.17763.1007
CLRVersion 4.0.30319.42000
WSManStackVersion 3.0
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1

vscode version : https://code.visualstudio.com/updates/v1_46

command that gave me the error
npx ng build --extractCss=true --subresourue --subresourceIntegrity=true

Does not play well with the contenthash path variable

webpack-subresource-integrity does not play well with the [contenthash] path variable.

For instance with the following webpack.config.js:

var SRIPlugin = require("webpack-subresource-integrity")

module.exports = {
  entry: "./src/index.js",
  mode: "production",
  output: {
    filename: "[name].[contenthash].js",
    chunkFilename: "[name].[contenthash].js",
  },
  plugins: [
    new SRIPlugin({
      enabled: true, // set to false to stop breakage
      hashFuncNames: [
        "sha256",
        "sha384",
      ],
    }),
  ],
}

I get the following output:

$ webpack --config webpack.config.js
Unhandled rejection Error: Path variable [contenthash] not implemented in this context: [name].[contenthash].js
    at fn (/Users/romeo/code/breaking-sri/node_modules/webpack/lib/TemplatedPathPlugin.js:43:11)
    at fn (/Users/romeo/code/breaking-sri/node_modules/webpack/lib/TemplatedPathPlugin.js:31:16)
    at String.replace (<anonymous>)
    at replacePathVariables (/Users/romeo/code/breaking-sri/node_modules/webpack/lib/TemplatedPathPlugin.js:99:5)
    at SyncWaterfallHook.eval [as call] (eval at create (/Users/romeo/code/breaking-sri/node_modules/tapable/lib/HookCodeFactory.js:17:12), <anonymous>:7:16)
    at MainTemplate.getAssetPath (/Users/romeo/code/breaking-sri/node_modules/webpack/lib/MainTemplate.js:474:31)
    at Object.getChunkFilename (/Users/romeo/code/breaking-sri/node_modules/webpack-subresource-integrity/util.js:130:50)
    at Array.from.reverse.forEach.childChunk (/Users/romeo/code/breaking-sri/node_modules/webpack-subresource-integrity/index.js:191:23)
    at Array.forEach (<anonymous>)
    at SubresourceIntegrityPlugin.processChunk (/Users/romeo/code/breaking-sri/node_modules/webpack-subresource-integrity/index.js:185:48)
    at forEachChunk (/Users/romeo/code/breaking-sri/node_modules/webpack-subresource-integrity/index.js:223:12)
    at Array.forEach (<anonymous>)
    at SubresourceIntegrityPlugin.afterOptimizeAssets (/Users/romeo/code/breaking-sri/node_modules/webpack-subresource-integrity/index.js:222:52)
    at SyncHook.eval [as call] (eval at create (/Users/romeo/code/breaking-sri/node_modules/tapable/lib/HookCodeFactory.js:17:12), <anonymous>:7:1)
    at SyncHook.lazyCompileHook [as _call] (/Users/romeo/code/breaking-sri/node_modules/tapable/lib/Hook.js:35:21)
    at hooks.optimizeAssets.callAsync.err (/Users/romeo/code/breaking-sri/node_modules/webpack/lib/Compilation.js:981:38)
    at AsyncSeriesHook.eval [as callAsync] (eval at create (/Users/romeo/code/breaking-sri/node_modules/tapable/lib/HookCodeFactory.js:24:12), <anonymous>:6:1)
    at AsyncSeriesHook.lazyCompileHook [as _callAsync] (/Users/romeo/code/breaking-sri/node_modules/tapable/lib/Hook.js:35:21)
    at hooks.optimizeChunkAssets.callAsync.err (/Users/romeo/code/breaking-sri/node_modules/webpack/lib/Compilation.js:977:32)
    at _err0 (eval at create (/Users/romeo/code/breaking-sri/node_modules/tapable/lib/HookCodeFactory.js:24:12), <anonymous>:11:1)
    at /Users/romeo/code/breaking-sri/node_modules/uglifyjs-webpack-plugin/dist/index.js:334:11
    at step (/Users/romeo/code/breaking-sri/node_modules/uglifyjs-webpack-plugin/dist/uglify/index.js:90:11)
    at done (/Users/romeo/code/breaking-sri/node_modules/uglifyjs-webpack-plugin/dist/uglify/index.js:99:22)
    at tryCatcher (/Users/romeo/code/breaking-sri/node_modules/bluebird/js/release/util.js:16:23)
    at Promise._settlePromiseFromHandler (/Users/romeo/code/breaking-sri/node_modules/bluebird/js/release/promise.js:512:31)
    at Promise._settlePromise (/Users/romeo/code/breaking-sri/node_modules/bluebird/js/release/promise.js:569:18)
    at Promise._settlePromise0 (/Users/romeo/code/breaking-sri/node_modules/bluebird/js/release/promise.js:614:10)
    at Promise._settlePromises (/Users/romeo/code/breaking-sri/node_modules/bluebird/js/release/promise.js:693:18)
    at Promise._fulfill (/Users/romeo/code/breaking-sri/node_modules/bluebird/js/release/promise.js:638:18)
    at Promise._resolveCallback (/Users/romeo/code/breaking-sri/node_modules/bluebird/js/release/promise.js:432:57)
    at Promise._settlePromiseFromHandler (/Users/romeo/code/breaking-sri/node_modules/bluebird/js/release/promise.js:524:17)
    at Promise._settlePromise (/Users/romeo/code/breaking-sri/node_modules/bluebird/js/release/promise.js:569:18)
    at Promise._settlePromise0 (/Users/romeo/code/breaking-sri/node_modules/bluebird/js/release/promise.js:614:10)
    at Promise._settlePromises (/Users/romeo/code/breaking-sri/node_modules/bluebird/js/release/promise.js:693:18)
    at Promise._fulfill (/Users/romeo/code/breaking-sri/node_modules/bluebird/js/release/promise.js:638:18)
    at Promise._resolveCallback (/Users/romeo/code/breaking-sri/node_modules/bluebird/js/release/promise.js:432:57)

My limited understanding of the issue is that webpack-subresource-integrity tries to interpolate the filenames in getChunkFilename and that fails because the [contenthash] is not calculated yet at the point webpack-subresource-integrity runs (in the after-optimize-assets hook).

I suggest suggest doing one of two things:

  • Do not try to interpolate the asset names at all
  • Move to a later hook that does have the contenthash

I've created a repo that reproduces this issue: https://github.com/romeovs/breaking-sri-contenthash

Resources in subfolders not found

It seems like the plugin has problems with resources located in subfolders.

My webpack output dir looks something like:

dist
โ”œโ”€styles
โ”‚  โ”œโ”€โ”€*.css
โ”œโ”€images
โ”‚  โ”œโ”€โ”€...
โ”œโ”€js
โ”‚  โ”œโ”€โ”€*.js
โ””โ”€index.html

Using the 'webpack-subresource-integrity' (in combination with the html-webpack-plugin), the following warning occurs for all resources:

WARNING in webpack-subresource-integrity: cannot determine hash for asset 'js/entry.js', the resource will be unprotected.

After some debugging, the issue seems to be in index.js#L164. compilation.assets stores all assets with path, the src parameter includes the path as well, but then path.basename(src) removes the path. As a result, the property lookup in compilation.assets fails (i.e. compilation.assets[path.basename(src)] doesn't return a asset).

image

working in mode:development but not 'production'

I have webpack bundling 3 files and using your plugin with the webpack-manifest plugin to pass these files an integrity Hash.
My issue is that when this is run on mode:production, 1 (sometimes 2) of the files get this error:
Failed to find a valid digest in the 'integrity' attribute for resource...
is there something specific I have to do for production mode which may be minifying or changing the files somehow?

it works fine in development mode

Integrity check error with webpack runtime file

Hello,

We started to use webpack-subresource-integrity plugin in my company, and I noticed some integrity errors because of our webpack runtime file and the browser cache. In some cases, it is possible to generate a runtime file with a name which does not change but where the content changed ([name].[contenthash].js). So if the runtime file (with this same name) is in the user browser cache (because long term caching) and the index.html file is loaded with the new integritry hash (because no long term caching for index.html): an integrity error occurs.

I created a repository in which you can reproduce this issue: https://github.com/sebastiendavid/webpack-sri-runtime-hash-issue

Steps to reproduce issue

  • Install node modules
npm ci
  • Build project
npm run build
  • Copy runtime file:
cp build/runtime.94ebc40d8dbd2fa73811.js runtime1.js
  • Change src/modules/moduleA content, for example:

Before:

import React from 'react';

export default function ModuleA() {
  return <div>ModuleA</div>;
}

After:

import React from 'react';

export default function ModuleA() {
  return <div>ModuleA FOOBAR</div>;
}
  • Build again
npm run build
  • Copy runtime file: build/runtime.94ebc40d8dbd2fa73811.js.
cp build/runtime.94ebc40d8dbd2fa73811.js runtime2.js

Notice that the hash in the filename did not change.

  • Compare the 2 runtime files
diff runtime1.js runtime2.js
var sriHashes = {
  "vendors": "sha256-yg3QzpkruWNm6WDkQxkfriaJxgtrrkRt8Q0dHCJQq90=",
- "app": "sha256-mvIw4Dp56Bv+nKsu9opwjBXHjonZgZ74q/HELYx401A=",
+ "app": "sha256-jlJ+6K39QeYSRDEzkeFV9NpXhrAULzxUAJTG1RtjBVg=",
  "moduleB": "sha256-GHBHstHDefAN+5Hv7+vVQj5fK0qzELaR/nkh75mVJjk=",
  "moduleC": "sha256-CLQxfIsv0UujQXZL1Ezz3Rb/guLqcWahQjSGnaebpuQ="
};

Subresource integrity hash from app chunk changed.

  • So the runtime filename did not change, but the content did. So if this file is cached by the browser and loaded from this cache: an integrity error occurs.

Bug when using the plugin

Hello,

Thanks you for this plugin. I'm actually getting a very weird bug while using your plugin.

Here is the error:

Error parsing 'integrity' attribute ('---CHUNK-SRI-HASH-1---'). The specified hash algorithm must be one of 'sha256', 'sha384', or 'sha512'.
requireEnsure @ main.3bf4ea4โ€ฆ.js:8036
(anonymous) @ category.3bf4ea4โ€ฆ.js:44
webpack_require @ main.3bf4ea4โ€ฆ.js:7395
webpackJsonpCallback @ main.3bf4ea4โ€ฆ.js:22
(anonymous) @ category.3bf4ea4โ€ฆ.js:1

Error parsing 'integrity' attribute ('---CHUNK-SRI-HASH-16---'). The specified hash algorithm must be one of 'sha256', 'sha384', or 'sha512'.

[the number change often, sometime it's like this for all chunks]

Also, I noticed that sometime (when running webpack), the stuff you put in the JS is not even present (but the integrity tags etc on js/css files are correctly there in the HTML)

The causing code:

All requires seems to be concerned but here is an example of a require I do

require(['./includes/js/MenusSlider'], (MenusSlider) => {
     return (new MenusSlider(defines.MenusSlider));
});

and the SRI plugin part in Webpack:
https://gist.github.com/pwnsdx/b73aa8baf8d11c4be3570f08cd84b1d3

Which is very big probably because of that bug...

I hope we can find a way to fix this issue and make this plugin better. If you need any informations feel free to ask me.

S.

infinite loop in findDepChunks

Hi -

We have a fairly large project and when we include this plugin, we get a maximum callback error. I've traced it down do the findDepChunks. If I move the recursive call into the if check, it works. I think depending on how you have lazy loading modules you can get chunks that are dependent on other chunks therefore by moving the recursive call, it seems to fix and I'm able to see the desired results.

If this is correct, I can make a PR for this fix.

Thanks.

--Adam

EDIT: we are using webpack 2.2.1 (we ran ng eject from angular-cli and added this plugin)

Integrity fail with Critters

Hi,

I'm using Critters to deal with critical css.
Critters is running after the webpack build. Can we deal with this and recalculate the integrity value on .css links processed with Critters ?

I'm getting a browser integrity value failed.

Compressed files - integrity problem

Hi, in my Angular 9 app I'm using ngx-build-plus for extending internal webpack configuration, because I want to pre-built also gzip and brotli files with this plugin
compression-webpack-plugin
. Everything works fine, gzipped and brotlied files are ok. The problem is when I try to build Angular application with --subresource-integrity flag. Adding this flag it simply enables this webpack-subresource-integrity plugin under the hood in Angular CLI and outputs integrity attributes for script and style elements in index.html.

Then the problem is that this plugin computes integrity hashes from original files but not compressed ones. If browser supports gzip or brotli encoding, then server sent those static assets (js, css, ...) compressed instead of original one so the problem is that hash does not match. The question is, if it is possible to solve it somehow. As you can see in this proposal, there is possibility to use multiple values of same hash. So is it possible to collaborate with compression-webpack-plugin, so this plugin outputs all possible hashes for 1 file (original, gzipped, brotli, etc.). Then from what is written here and in proposal, seems that browsers should match only one from those and everything should work. Thanks.

Plugin doesn't work with webpack watch

When using this plugin with webpack watch, the first build succeed but after that, it produces integrity="null".

Btw, I see you mentioning problems with hot reloading in README, does this apply to webpack watch too?

Always get "Chunks loaded by HMR are unprotected" warning

Hello! It seems that I always get the following warning when I use webpack-dev-server even if HMR is not enabled:

WARNING in webpack-subresource-integrity: Chunks loaded by HMR are unprotected. Consider disabling webpack-subresource-integrity in development mode.

Versions:
"webpack": "^2.5.0",
"webpack-dev-server": "^2.4.5"

Cannot determine asset for chunk

PS F:\code\cloverleaf\web> npm run build   

> [email protected] build F:\code\cloverleaf\web
> cross-env NODE_ENV=production node --no-deprecation config/webpack/config.js

Translations up to date
Processing translations
Finished processing translations
Build completed in 8.39s

Hash: 7f2e0fa3729cfe31f2e7
Version: webpack 5.0.0-beta.28        
Time: 8388 ms
Built at: 2020-08-21 06:42:40
asset ..\de-DE.html 7.95 KiB [emitted]
asset ..\eo-UY.html 7.92 KiB [emitted]
asset ..\es-ES.html 8.1 KiB [emitted] 
asset ..\fr-FR.html 8.04 KiB [emitted]
asset ..\index.html 7.83 KiB [emitted]
asset bundle-12384be5.css 72.5 KiB [emitted] [immutable] (name: main)
asset bundle-268b812b.js 116 KiB [emitted] [immutable] [minimized] (name: main) 1 related asset
asset fonts/MaterialIcons-Regular.eot 67.6 KiB [emitted] (auxiliary name: main)
asset fonts/MaterialIcons-Regular.ttf 170 KiB [emitted] (auxiliary name: main)
asset fonts/MaterialIcons-Regular.woff 77.7 KiB [emitted] (auxiliary name: main)
asset fonts/MaterialIcons-Regular.woff2 59.4 KiB [emitted] (auxiliary name: main)
asset fonts/Roboto-Light.ttf 166 KiB [emitted] (auxiliary name: main)
asset fonts/Roboto-Medium.ttf 168 KiB [emitted] (auxiliary name: main)
asset fonts/Roboto-Regular.ttf 168 KiB [emitted] (auxiliary name: main)
asset fonts/RobotoMono-Regular.ttf 112 KiB [emitted] (auxiliary name: main)
asset sitemap.xml 885 bytes [emitted]
asset sitemap.xml.gz 266 bytes [emitted]
Entrypoint main = bundle-12384be5.css bundle-268b812b.js (fonts/MaterialIcons-Regular.eot fonts/MaterialIcons-Regular.ttf fonts/MaterialIcons-Regular.woff fonts/MaterialIcons-Regular.woff2 fonts/Roboto-Light.ttf fonts/Roboto-Medium.ttf fonts/Roboto-Regular.ttf fonts/RobotoMono-Regular.ttf)
./src/main.js 20 KiB [built]
./node_modules/@babel/runtime/helpers/defineProperty.js 289 bytes [built]
./node_modules/@babel/runtime/helpers/typeof.js 479 bytes [built]
./node_modules/materialize-css/js/cash.js 22.3 KiB [built]
./node_modules/materialize-css/js/component.js 1.07 KiB [built]
./node_modules/materialize-css/js/global.js 12.4 KiB [built]
./node_modules/materialize-css/js/anime.min.js 14 KiB [built]
./node_modules/materialize-css/js/tooltip.js 8.02 KiB [built]
./node_modules/materialize-css/js/forms.js 8.39 KiB [built]
./node_modules/materialize-css/js/autocomplete.js 11.7 KiB [built]
./node_modules/materialize-css/js/tabs.js 10.5 KiB [built]
./node_modules/materialize-css/js/sidenav.js 16.2 KiB [built]
./node_modules/materialize-css/js/toasts.js 7.83 KiB [built]
./node_modules/materialize-css/js/buttons.js 8.92 KiB [built]
./node_modules/materialize-css/js/dropdown.js 17.9 KiB [built]
    + 27 hidden modules

WARNING in webpack-subresource-integrity: Cannot determine asset for chunk 179, computed="bundle-66e5d323.js", available=bundle-12384be5.css. Please report this full error message along with your Webpack configuration at https://github.com/waysact/webpack-subresource-integrity/issues/new

Here's my config: https://github.com/cloverleaf/web/blob/master/config/webpack/config.js

SRI can't be determined with 0.5.1 release

After moving to 0.5.1 I'm now finding all of my chunks fail to generate a hash. (not using html-webpack-plugin)

Example:

WARNING in webpack-subresource-integrity: cannot determine hash for asset '../../../../../vendor.bundle.0e48a883951098cad7a7.js', the resource will be unprotected.
WARNING in webpack-subresource-integrity: cannot determine hash for asset '../../../../../app.bundle.0e48a883951098cad7a7.js', the resource will be unprotected.

Webpack 5

  • Test with optimization.realContentHash
  • Remove webpack-sources dependency in favor of require("webpack").sources

Compatibility with optimize-css-assets-webpack-plugin

Whenever I use this plugin in combination with optimize-css-assets-webpack-plugin, the resulting link tag generates the incorrect integrity attribute, and therefore prevents the CSS from loading in browser:

Failed to find a valid digest in the 'integrity' attribute for resource 'https://xxx/style.415f2b53c2098ba7dfd1271ff3ea863b.css' with computed SHA-256 integrity 'TSiEV9m8u3ydiUrNtjVJ2VK3P/LRhVT1v11HpKQFCjU='. The resource has been blocked

Disabling the optimize-css-assets-webpack-plugin plugin fixes the error.

    new OptimizeCssAssetsPlugin(), // comment-out to fix build
    new SriPlugin({ hashFuncNames: ['sha256', 'sha512'] }),

Versions

    "optimize-css-assets-webpack-plugin": "^2.0.0",
    "webpack": "^2.6.1",
    "webpack-subresource-integrity": "^1.0.0-rc.1"

I'll try putting together a reproduction tomorrow.

New configuration options: enabled, crossorigin

It should be possible to disable the plugin (e.g. in development mode) and configure the crossorigin attribute for html-webpack-plugin injection. To this end, the current configuration syntax is now deprecated and will be replaced by a standard key/value based option argument.

The old plugin initialization looks like this:

new SriPlugin(['sha256', 'sha384']) // multiple hash function names, or
new SriPlugin('sha512') // single hash function name

This is replaced by:

new SriPlugin({
    hashFuncNames: ['sha512'],
})

Note that a single hash function name also needs to be wrapped in an array.

The new syntax is supported from 0.7.0 onwards. The old configuration syntax is still supported but will cause a deprecation warning to be output via Webpack facilities, and will be removed in a future 1.0.0 release.

This change introduces the enabled option, which users should consider setting to a falsy value outside of production. It also introduces the crossorigin option, which users will want to leave at its default value (anonymous) in most cases. See the new README for details.

Don't crash when used in non-web builds

On Nuxt.js 2.0.0

import SriPlugin from 'webpack-subresource-integrity';
module.exports = {
  build: {
    extend(config, ctx) {
      config.output.crossOriginLoading = 'anonymous'
      config.plugins.push(new SriPlugin({
        hashFuncNames: ['sha256', 'sha384']
      }))
    }
  }
}

This setting triggers this error

โœ– error TypeError: Cannot read property 'tap' of undefined
  at WebIntegrityJsonpMainTemplatePlugin.apply (/Users/inductor/vue/project/node_modules/webpack-subresource-integrity/jmtp.js:76:36)
  at SubresourceIntegrityPlugin.registerJMTP (/Users/inductor/vue/project/node_modules/webpack-subresource-integrity/index.js:302:12)
  at SubresourceIntegrityPlugin.thisCompilation (/Users/inductor/vue/project/node_modules/webpack-subresource-integrity/index.js:348:10)
  at SyncHook.eval [as call] (eval at create (/Users/inductor/vue/project/node_modules/tapable/lib/HookCodeFactory.js:19:10), <anonymous>:13:1)
  at SyncHook.lazyCompileHook (/Users/inductor/vue/project/node_modules/tapable/lib/Hook.js:154:20)
  at Compiler.newCompilation (/Users/inductor/vue/project/node_modules/webpack/lib/Compiler.js:497:30)
  at hooks.beforeCompile.callAsync.err (/Users/inductor/vue/project/node_modules/webpack/lib/Compiler.js:534:29)
  at AsyncSeriesHook.eval [as callAsync] (eval at create (/Users/inductor/vue/project/node_modules/tapable/lib/HookCodeFactory.js:32:10), <anonymous>:6:1)
  at AsyncSeriesHook.lazyCompileHook (/Users/inductor/vue/project/node_modules/tapable/lib/Hook.js:154:20)
  at Compiler.compile (/Users/inductor/vue/project/node_modules/webpack/lib/Compiler.js:529:28)
  at readRecords.err (/Users/inductor/vue/project/node_modules/webpack/lib/Compiler.js:268:11)
  at Compiler.readRecords (/Users/inductor/vue/project/node_modules/webpack/lib/Compiler.js:396:11)
  at hooks.run.callAsync.err (/Users/inductor/vue/project/node_modules/webpack/lib/Compiler.js:265:10)
  at AsyncSeriesHook.eval [as callAsync] (eval at create (/Users/inductor/vue/project/node_modules/tapable/lib/HookCodeFactory.js:32:10), <anonymous>:6:1)
  at AsyncSeriesHook.lazyCompileHook (/Users/inductor/vue/project/node_modules/tapable/lib/Hook.js:154:20)
  at hooks.beforeRun.callAsync.err (/Users/inductor/vue/project/node_modules/webpack/lib/Compiler.js:262:19)

Make it easier to render script tags with SRI data

When not using the html-webpack-plugin, one needs to write a fair amount of custom code to render a script tag with proper SRI attributes for each asset.

I'd like to propose a new saveAs option to make this easier. It would look like this:

import SriPlugin from 'webpack-subresource-integrity';

const plugins = [
    new SriPlugin({
        hashFuncNames: ['sha512'],
        saveAs: path.join(__dirname, 'dist', 'sri-mapping.json'),
    }),
];

It would write a JSON file that gives you all the data you need to construct script tags:

{
  "crossOriginLoading": "anonymous",
  "integrityValues": {
     "bundle1-3d9b377092c96e232575.js" : "sha512-3zYQGpoq6KJ4D...",
     "bundle2-385668e5e9c5eb1bbc7e.js" : "sha512-n8tGFPkzPLMGltk..."
  }
}

In any server view that writes an index page, one could then easily create a script tag like:

const baseName = filePath.split('/').pop();
return `<script  
  src="${filePath}" 
  integrity="${sriMapping.integrityValues[baseName]}" 
  crossOrigin="${sriMapping.crossOriginLoading}"
/>`;

Would you accept a patch for this?

BTW, this interface is what I was using in sri-stats-webpack but that one doesn't support webpack 2 so I have to migrate. The approached worked well enough for a universal React app.

Interaction with webpack-manifest-plugin

Hey there,

I'm using https://github.com/danethurber/webpack-manifest-plugin in my project and it appears to be incompatible with this SRI plugin. Much sadness was had.

To be more precise :

When both plugins are enabled, the SRI plugin fails to replace the placeholder string with the actual SRI map in the anonymous chunks' bootstrap code. I've dug a bit (but not entirely yet), and it boils down to https://github.com/waysact/webpack-subresource-integrity/blob/master/index.js#L220 this yielding the chunk manifest instead of the intended source.
As a result, the chunk scripts are inserted with placeholder values in the integrity="" attributes.

I'm not sure if I should be filing this here or at webpack-manifest-plugin, but I thought I'd start here.

I actually need to solve this so I'm going to debug this a bit anyway. I'll keep you posted if something relevant comes up.

WARNING in webpack-subresource-integrity: Cannot determine asset for chunk scripts, computed="undefined"

Here is the warning:

WARNING in webpack-subresource-integrity: Cannot determine asset for chunk scripts, computed="undefined", available=scripts.a6bfd8cd0af627017117.js. Please report this full error message along with your Webpack configuration at https://github.com/waysact/webpack-subresource-integrity/issues/new

here is code

function googleTranslateElementInit(){"undefined"!=typeof google&&new google.translate.TranslateElement({pageLanguage:"en",layout:google.translate.TranslateElement.InlineLayout.SIMPLE},"google_translate_element")}!function(e){var t={};function n(a){if(t[a])return t[a].exports;var o=t[a]={i:a,l:!1,exports:{}};return e[a].call(o.exports,o,o.exports,n),o.l=!0,o.exports}n.m=e,n.c=t,n.d=function(e,t,a){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:a})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var a=Object.create(null);if(n.r(a),Object.defineProperty(a,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(a,o,(function(t){return e[t]}).bind(null,o));return a},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=0)}([function(e,t){"undefined"!=typeof window&&(window.VERSION="2019-04-15T05:35:55.417Z")}]),function(e,t,n,a,o,r,l){e.GoogleAnalyticsObject="ga",e.ga=e.ga||function(){(e.ga.q=e.ga.q||[]).push(arguments)},e.ga.l=1*new Date,r=t.createElement(n),l=t.getElementsByTagName(n)[0],r.async=1,r.src="https://www.google-analytics.com/analytics.js",l.parentNode.insertBefore(r,l)}(window,document,"script"),function(e,t,n){e&&t&&function(e,t){var n=new Date;function a(e){var n=t.getElementsByTagName("head")[0];n||(n=t.body.parentNode.appendChild(t.createElement("head"))),n.appendChild(e)}e.addEventListener&&void 0===t.readyState&&e.addEventListener("DOMContentLoaded",function(){t.readyState="complete"},!1),function(t){t=t.split(".");for(var n=e,a=0;a<t.length;++a)if(!(n=n[t[a]]))return!1;return!0}("google.translate.Element")||function(){var o=function(t){t=t.split(".");for(var n=e,a=0;a<t.length;++a)n=n.hasOwnProperty?n.hasOwnProperty(t[a])?n[t[a]]:n[t[a]]={}:n[t[a]]||(n[t[a]]={});return n}("google.translate._const");o._cest=n,n=void 0,o._cl="en",o._cuc="googleTranslateElementInit",o._cac="",o._cam="",o._ctkk="427170.2388829369";var r,l="translate.googleapis.com",i="https://",s=i+l;o._pah=l,o._pas=i,o._pbi=s+"/translate_static/img/te_bk.gif",o._pci=s+"/translate_static/img/te_ctrl3.gif",o._pli=s+"/translate_static/img/loading.gif",o._plla=l+"/translate_a/l",o._pmi=s+"/translate_static/img/mini_google.png",o._ps=s+"/translate_static/css/translateelement.css",o._puh="translate.google.com",function(e){var n=t.createElement("link");n.type="text/css",n.rel="stylesheet",n.charset="UTF-8",n.href=e,a(n)}(o._ps),(r=t.createElement("script")).type="text/javascript",r.charset="UTF-8",r.src="https://translate.googleapis.com/translate_static/js/element/main.js",a(r)}()}(e,t)}("undefined"!=typeof window?window:null,"undefined"!=typeof document?document:null);

[Bug] thisCompilation.mainTemplate is never hit

Using this plugin in our webpack build produces no difference to the output webpackJsonp function. After some debugging, it looks as if the code within the this-compilation plugin is never getting called.

If I change the following lines:

  compiler.plugin('compilation', function compilationPlugin(compilation) {
    /*
     * Double plug-in registration in order to push our
     * plugin to the end of the plugin stack.
     */
    compiler.plugin('this-compilation', function thisCompilationPlugin(thisCompilation) {
      thisCompilation.mainTemplate.apply(new WebIntegrityJsonpMainTemplatePlugin());
    });

To this:

  compiler.plugin('compilation', function compilationPlugin(compilation) {
    /*
     * Double plug-in registration in order to push our
     * plugin to the end of the plugin stack.
     */
    compilation.mainTemplate.apply(new WebIntegrityJsonpMainTemplatePlugin());

It works.

Looking at the webpack source code, it looks like this-compilation event/plugin actually fires before compilation, not after, so this code will never get hit.

html-webpack-plugin should be a peer dependency, or not directly require()'d

As it happens; webpack-subresource-integrity makes a require('html-webpack-plugin') call, but doesn't list it anywhere in its dependencies (not even as a peer dependency).

While it works on most installs at the moment, it's only by accident, and package managers offer no guarantee that this will hold true much longer; in fact, it breaks now with Plug'n'Play and likely with pnpm as well.

Adding webpack-subresource-integrity as a peer dependency would have the unfortunate side effect that users would get a warning, but that's a separate (non-blocking, I hope, since it's purely visual) problem that should be solved on the package managers side ๐Ÿ™‚

Cannot determine asset for chunk 1

WARNING in webpack-subresource-integrity: Cannot determine asset for chunk 1, computed="style-bcdc400faeee6f1e1853.js", available=style-9a9a610f150286f63b30.css. Please report this full error message along with your Webpack configuration at https://github.com/waysact/webpack-subresource-integrity/issues/new

const chunkHash = require('webpack-chunk-hash');
const copy = require('copy-webpack-plugin');
const exclude = require('html-webpack-exclude-assets-plugin');
const extension = require('script-ext-html-webpack-plugin');
const extract = require('mini-css-extract-plugin');
const html = require('html-webpack-plugin');
const inline = require('html-webpack-inline-source-plugin');
const path = require('path');
const workbox = require('workbox-webpack-plugin');
const sri = require('webpack-subresource-integrity');

const production = process.env.NODE_ENV === 'production';

module.exports = {
  context: path.resolve(__dirname, 'src'),
  mode: production ? 'production' : 'development',
  entry: './index.ts',
  devServer: {
    contentBase: path.resolve(__dirname, 'src'),
    hot: false
  },
  output: {
    crossOriginLoading: 'anonymous',
    chunkFilename: '[name]-[chunkhash].js',
    filename: '[name]-[contenthash].js',
    path: path.resolve(__dirname, 'public'),
  },
  optimization: {
    splitChunks: {
      cacheGroups: {
        styles: {
          name: 'style',
          test: /\.css$/,
          chunks: 'all',
          enforce: true
        }
      }
    }
  },
  plugins: [
    new extract({ filename: '[name]-[contenthash].css' }),
    new html({
      excludeAssets: [/style-.*\.js/],
      filename: 'index.html',
      inlineSource: '.(css)$',
      template: path.resolve(__dirname, 'src', 'index.html'),
    }),
    new inline(),
    new chunkHash(),
    new extension({ defaultAttribute: 'async' }),
    new workbox.InjectManifest({
      swSrc: path.resolve(__dirname, 'src', 'sw.js'),
      swDest: 'sw.js',
    }),
    new copy([
      {
        from: '*.txt',
        to: '.',
      },
      {
        from: '*.ico',
        to: '.',
      },
      {
        from: '*.png',
        to: '.',
      },
      {
        from: 'img/*',
        to: '.',
      },
      {
        from: '*.json',
        to: '.',
      },
    ]),
    new sri({
      hashFuncNames: ['sha256', 'sha384'],
      enabled: production,
    }),
  ],
  module: {
    rules: [
      { test: /\.tsx?$/, loader: "ts-loader" },
      {
        test: /\.css$/,
        use: [
          extract.loader,
          'css-loader',
          {
            loader: 'sass-loader',
            options: {
              includePaths: [path.resolve(__dirname, 'node_modules')]
            },
          },
        ],
      },
    ],
  },
};

This is with a slight modification of my personal site. filename: '[name]-[chunkhash].js' to filename: '[name]-[contenthash].js'

Issue with <link rel="preload">

Hi!

Thanks for this plugin!

It looks like Chrome (probably other browsers too) have issues with the combination of SRI and <link rel="preload">

You might want to put in the notes that this, combined with /* webpackPreload: "true" */ of lazy chunks will break the preloading mechanism until <link rel="preload"> also supports SRI:

w3c/preload#127

For us, that means disabling this plugin for now, since we need to be able to preload the lazy chunks for performance reasons as to not have a double-fetch for a resource.

Upgrading to the html-webpack-plugin version 4

The html-webpack-plugin version 4 is getting closer to a release.
Many information can be found in this pr: jantimon/html-webpack-plugin#953

A static version property was added:
https://github.com/jantimon/html-webpack-plugin/blob/d65b37d2c588047e0d81a38f4645fcdb3ead0b9e/index.js#L915-L927

The event system was changed alot to work with the new features:

Could you please give the new events a try and let me know if they work for your case?
https://github.com/jantimon/html-webpack-plugin/tree/webpack-4#events

beforeAssetTagGeneration hook

    AsyncSeriesWaterfallHook<{
      assets: {
        publicPath: string,
        js: Array<{string}>,
        css: Array<{string}>,
        favicon?: string | undefined,
        manifest?: string | undefined
      },
      outputName: string,
      plugin: HtmlWebpackPlugin
    }>

alterAssetTags hook

    AsyncSeriesWaterfallHook<{
      assetTags: {
        scripts: Array<HtmlTagObject>,
        styles: Array<HtmlTagObject>,
        meta: Array<HtmlTagObject>,
      },
      outputName: string,
      plugin: HtmlWebpackPlugin
    }>

alterAssetTagGroups hook

    AsyncSeriesWaterfallHook<{
      headTags: Array<HtmlTagObject | HtmlTagObject>,
      bodyTags: Array<HtmlTagObject | HtmlTagObject>,
      outputName: string,
      plugin: HtmlWebpackPlugin
    }>

afterTemplateExecution hook

    AsyncSeriesWaterfallHook<{
      html: string,
      headTags: Array<HtmlTagObject | HtmlTagObject>,
      bodyTags: Array<HtmlTagObject | HtmlTagObject>,
      outputName: string,
      plugin: HtmlWebpackPlugin,
    }>

beforeEmit hook

    AsyncSeriesWaterfallHook<{
      html: string,
      outputName: string,
      plugin: HtmlWebpackPlugin,
    }>

afterEmit hook

    AsyncSeriesWaterfallHook<{
      outputName: string,
      plugin: HtmlWebpackPlugin
    }>

`crossOriginLoading: false` defaults to `anonymous`

It appears crossOriginLoading: false doesn't work. When I set the value to false, a valid option, I still receive the warning WARNING in webpack-subresource-integrity: Set webpack option output.crossOriginLoading when using this plugin.. Perhaps webpack-subresource-integrity is checking for a falsy value, instead of a more specific crossOriginLoading !== undefined && crossOriginLoading !== null? If I ignore the warning and leave the crossOriginLoading as false, it defaults to anonymous.

WARNING in webpack-subresource-integrity: Cannot determine asset for chunk scripts, computed="undefined", available=scripts.2b355891e0dd05f2cdd5.js.

 ng build --prod --subresource-integrity

                                                                                   
Date: 2019-02-04T14:48:54.230Z
Hash: e8ec25d629e6dd81be68
Time: 119010ms
chunk {0} runtime.76b8cb0dd56312a4d1c7.js (runtime) 2.66 kB [entry] [rendered]
chunk {1} main.36a8afa8424de3afa8ad.js (main) 4.45 MB [initial] [rendered]
chunk {2} polyfills.c6cdf1b91f8032c61d53.js (polyfills) 97.4 kB [initial] [rendered]
chunk {3} styles.51c1ea8fe537fad875ea.css (styles) 283 kB [initial] [rendered]
chunk {4} 4.ecbabf05799fd4bb45c2.js () 3.48 kB  [rendered]
chunk {5} 5.a5a29fb287559e9f39b1.js () 3.63 kB  [rendered]
chunk {scripts} scripts.2b355891e0dd05f2cdd5.js (scripts) 950 kB [entry] [rendered]

`WARNING in webpack-subresource-integrity: Cannot determine asset for chunk scripts, computed="undefined", available=scripts.2b355891e0dd05f2cdd5.js. Please report this full error message along with your Webpack configuration at https://github.com/waysact/webpack-subresource-integrity/issues/new`

"@angular/cli": "7.3.0",
 "@angular/core": "7.2.3",
Node : v10.4.1

Cannot determine asset for chunk

Please forgive me if this was already reported, however, I believe my situation to be different.

WARNING in webpack-subresource-integrity: Cannot determine asset for chunk 24, computed="style.js", available=style.css. Please report this full error message along...

This happens because I am extracting CSS styles from style.js using mini-css-extract-plugin and removing the now empty style.js file using webpack-fix-style-only-entries. Here is a sample Webpack configuration demonstrating the issue.

const path = require('path');
const FixStyle = require('webpack-fix-style-only-entries');
const Extract = require('mini-css-extract-plugin');
const HTML = require('html-webpack-plugin');
const SRI = require('webpack-subresource-integrity');

module.exports =
{
	mode: 'production',
	context: path.join(process.cwd(), 'source/'),

	entry:
	{
		style: [ 'styles/style'  ],
		entry: [ 'scripts/entry' ]
	},

	output:
	{
		crossOriginLoading: 'anonymous',
		chunkFilename: '[name]-[chunkhash].js',
		filename: '[name]-[contenthash].js',
		path: path.resolve(__dirname, 'public')
	},

	plugins:
	[
		new FixStyle(),

		new Extract({ filename: '[name]-[contenthash].css' }),

		new HTML
		({
			filename: 'index.html',
			template: 'index.ejs'
		}),

		new SRI({ hashFuncNames: [ 'sha384' ] })
	],

	module:
	{
		rules:
		[
			{
				test: /\.css$/,
				use: [ Extract.loader, 'css-loader' ]
			}
		]
	}
};

I am using [email protected]

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.