|
1 | 1 | module.exports = class CorsPlugin {
|
2 |
| - constructor ({ crossorigin, integrity }) { |
3 |
| - this.crossorigin = crossorigin || (integrity ? '' : undefined) |
| 2 | + constructor ({ baseUrl, crossorigin, integrity }) { |
| 3 | + this.crossorigin = crossorigin |
4 | 4 | this.integrity = integrity
|
| 5 | + this.baseUrl = baseUrl |
5 | 6 | }
|
6 | 7 |
|
7 | 8 | apply (compiler) {
|
8 | 9 | const ID = `vue-cli-cors-plugin`
|
9 | 10 | compiler.hooks.compilation.tap(ID, compilation => {
|
| 11 | + const ssri = require('ssri') |
| 12 | + |
| 13 | + const computeHash = url => { |
| 14 | + const filename = url.replace(this.baseUrl, '') |
| 15 | + const asset = compilation.assets[filename] |
| 16 | + if (asset) { |
| 17 | + const src = asset.source() |
| 18 | + const integrity = ssri.fromData(src, { |
| 19 | + algorithms: ['sha384'] |
| 20 | + }) |
| 21 | + return integrity.toString() |
| 22 | + } |
| 23 | + } |
| 24 | + |
10 | 25 | compilation.hooks.htmlWebpackPluginAlterAssetTags.tap(ID, data => {
|
| 26 | + const tags = [...data.head, ...data.body] |
11 | 27 | if (this.crossorigin != null) {
|
12 |
| - [...data.head, ...data.body].forEach(tag => { |
| 28 | + tags.forEach(tag => { |
13 | 29 | if (tag.tagName === 'script' || tag.tagName === 'link') {
|
14 | 30 | tag.attributes.crossorigin = this.crossorigin
|
15 | 31 | }
|
16 | 32 | })
|
17 | 33 | }
|
| 34 | + if (this.integrity) { |
| 35 | + tags.forEach(tag => { |
| 36 | + if (tag.tagName === 'script') { |
| 37 | + const hash = computeHash(tag.attributes.src) |
| 38 | + if (hash) { |
| 39 | + tag.attributes.integrity = hash |
| 40 | + } |
| 41 | + } else if (tag.tagName === 'link' && tag.attributes.rel === 'stylesheet') { |
| 42 | + const hash = computeHash(tag.attributes.href) |
| 43 | + if (hash) { |
| 44 | + tag.attributes.integrity = hash |
| 45 | + } |
| 46 | + } |
| 47 | + }) |
| 48 | + |
| 49 | + // when using SRI, Chrome somehow cannot reuse |
| 50 | + // the preloaded resource, and causes the files to be downloaded twice. |
| 51 | + // this is a Chrome bug (https://bugs.chromium.org/p/chromium/issues/detail?id=677022) |
| 52 | + // for now we disable preload if SRI is used. |
| 53 | + data.head = data.head.filter(tag => { |
| 54 | + return !( |
| 55 | + tag.tagName === 'link' && |
| 56 | + tag.attributes.rel === 'preload' |
| 57 | + ) |
| 58 | + }) |
| 59 | + } |
| 60 | + }) |
| 61 | + |
| 62 | + compilation.hooks.htmlWebpackPluginAfterHtmlProcessing.tap(ID, data => { |
| 63 | + data.html = data.html.replace(/\scrossorigin=""/g, ' crossorigin') |
18 | 64 | })
|
19 | 65 | })
|
20 | 66 | }
|
|
0 commit comments