├── .babelrc
├── .eslintignore
├── .eslintrc.js
├── .gitignore
├── .travis.yml
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── package-lock.json
├── package.json
├── src
├── index.js
└── lib
│ ├── create-html-element-string.js
│ ├── default-options.js
│ ├── determine-as-value.js
│ ├── extract-chunks.js
│ └── insert-links-into-head.js
└── test
├── .eslintrc.js
├── fixtures
├── file.js
├── font.woff2
├── home.js
├── load-css.js
├── module-a.js
├── style.css
└── vendor.js
├── spec.js
├── unit
├── create-html-element-string.js
├── determine-as-value.js
└── insert-links-into-head.js
├── webpack4-htmlplugin4
├── index.js
├── package-lock.json
└── package.json
└── webpack4
├── index.js
├── package-lock.json
└── package.json
/.babelrc:
--------------------------------------------------------------------------------
1 | {
2 | "presets": [
3 | ["@babel/preset-env", {
4 | "targets": {
5 | "node": "8.0.0"
6 | },
7 | }]
8 | ]
9 | }
10 |
--------------------------------------------------------------------------------
/.eslintignore:
--------------------------------------------------------------------------------
1 | build/
2 | demo/
3 | test/fixtures/
4 | test/*/node_modules/
5 |
--------------------------------------------------------------------------------
/.eslintrc.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | extends: ['eslint:recommended', 'google'],
3 | env: {
4 | node: true,
5 | es6: true,
6 | },
7 | parserOptions: {
8 | ecmaVersion: 2017,
9 | },
10 | rules: {
11 | 'max-len': [2, 140, {
12 | ignoreComments: true,
13 | ignoreUrls: true,
14 | tabWidth: 2
15 | }],
16 | 'require-jsdoc': 0,
17 | 'valid-jsdoc': 0,
18 | 'comma-dangle': 0,
19 | 'arrow-parens': 0,
20 | }
21 | };
22 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Directories
2 | .nyc_output/
3 | build/
4 | node_modules/
5 |
6 | # Files
7 | npm-debug.log
8 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: node_js
2 |
3 | node_js:
4 | - 8
5 |
6 | install:
7 | - npm ci && cd test/webpack4 && npm ci && cd ../webpack4-htmlplugin4 && npm ci && cd ../..
8 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # How to become a contributor and submit your own code
2 |
3 | ## Contributor License Agreements
4 |
5 | We'd love to accept your sample apps and patches! Before we can take them, we
6 | have to jump a couple of legal hurdles.
7 |
8 | Please fill out either the individual or corporate Contributor License Agreement
9 | (CLA).
10 |
11 | * If you are an individual writing original source code and you're sure you
12 | own the intellectual property, then you'll need to sign an [individual CLA]
13 | (https://developers.google.com/open-source/cla/individual).
14 | * If you work for a company that wants to allow you to contribute your work,
15 | then you'll need to sign a [corporate CLA]
16 | (https://developers.google.com/open-source/cla/corporate).
17 |
18 | Follow either of the two links above to access the appropriate CLA and
19 | instructions for how to sign and return it. Once we receive it, we'll be able to
20 | accept your pull requests.
21 |
22 | ## Contributing A Patch
23 |
24 | 1. Submit an issue describing your proposed change to the repo in question.
25 | 1. The repo owner will respond to your issue promptly.
26 | 1. If your proposed change is accepted, and you haven't already done so, sign a
27 | Contributor License Agreement (see details above).
28 | 1. Fork the desired repo, develop and test your code changes.
29 | 1. Ensure that your code adheres to the existing style in the sample to which
30 | you are contributing. Refer to the
31 | [Google Cloud Platform Samples Style Guide]
32 | (https://github.com/GoogleCloudPlatform/Template/wiki/style.html) for the
33 | recommended coding standards for this organization.
34 | 1. Ensure that your code has an appropriate set of unit tests which all pass.
35 | 1. Submit a pull request.
36 |
37 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright 2019 Google Inc.
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
203 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # preload-webpack-plugin
2 |
3 | > **DEPRECATED: A fork of this project, https://github.com/vuejs/preload-webpack-plugin can be used instead.**
4 |
5 | A webpack plugin for automatically wiring up asynchronous (and other types) of JavaScript
6 | chunks using ``. This helps with lazy-loading.
7 |
8 | Note: This is an extension plugin for [`html-webpack-plugin`](https://github.com/jantimon/html-webpack-plugin) - a plugin that
9 | simplifies the creation of HTML files to serve your webpack bundles.
10 |
11 | ## Introduction
12 |
13 | [Preload](https://w3c.github.io/preload/) is a web standard aimed at improving performance
14 | and granular loading of resources. It is a declarative fetch that can tell a browser to start fetching a
15 | source because a developer knows the resource will be needed soon. [Preload: What is it good for?](https://www.smashingmagazine.com/2016/02/preload-what-is-it-good-for/)
16 | is a recommended read if you haven't used the feature before.
17 |
18 | In simple web apps, it's straight-forward to specify static paths to scripts you
19 | would like to preload - especially if their names or locations are unlikely to change. In more complex apps,
20 | JavaScript can be split into "chunks" (that represent routes or components) at with dynamic
21 | names. These names can include hashes, numbers and other properties that can change with each build.
22 |
23 | For example, `chunk.31132ae6680e598f8879.js`.
24 |
25 | To make it easier to wire up async chunks for lazy-loading, this plugin offers a drop-in way to wire them up
26 | using ``.
27 |
28 | ## Prerequisites
29 |
30 | This module requires webpack v4 and above. It also requires that you're using
31 | [`html-webpack-plugin`](https://github.com/ampedandwired/html-webpack-plugin) in your webpack project.
32 |
33 | ## Installation
34 |
35 | First, install the package as a dependency in your `package.json`:
36 |
37 | ```sh
38 | $ npm install --save-dev preload-webpack-plugin
39 | ```
40 |
41 | ## Usage
42 |
43 | In your webpack config, `require()` the preload plugin as follows:
44 |
45 | ```js
46 | const PreloadWebpackPlugin = require('preload-webpack-plugin');
47 | ```
48 |
49 | and finally, add the plugin to your webpack configuration's `plugins` array after `HtmlWebpackPlugin`:
50 |
51 | ```js
52 | plugins: [
53 | new HtmlWebpackPlugin(),
54 | new PreloadWebpackPlugin()
55 | ]
56 | ```
57 |
58 | When preloading files, the plugin will use different `as` attribute depends on the type of each
59 | file. For each file ends with `.css`, the plugin will preload it with `as=style`, for each file ends
60 | with `.woff2`, the plugin will preload it with `as=font`, while for all other files, `as=script`
61 | will be used.
62 |
63 | If you do not prefer to determine `as` attribute depends on suffix of filename, you can also
64 | explicitly name it using `as`:
65 |
66 | ```javascript
67 | plugins: [
68 | new HtmlWebpackPlugin(),
69 | new PreloadWebpackPlugin({
70 | rel: 'preload',
71 | as: 'script'
72 | })
73 | ]
74 | ```
75 |
76 | In case you need more fine-grained control of the `as` attribute, you could also
77 | provide a function here. When using it, entry name will be provided as the
78 | parameter, and function itself should return a string for `as` attribute:
79 |
80 | ```javascript
81 | plugins: [
82 | new HtmlWebpackPlugin(),
83 | new PreloadWebpackPlugin({
84 | rel: 'preload',
85 | as(entry) {
86 | if (/\.css$/.test(entry)) return 'style';
87 | if (/\.woff$/.test(entry)) return 'font';
88 | if (/\.png$/.test(entry)) return 'image';
89 | return 'script';
90 | }
91 | })
92 | ]
93 | ```
94 |
95 | Notice that if `as=font` is used in preload, the `crossorigin` will also be
96 | added. Explains can be found in
97 | [this article](https://medium.com/reloading/preload-prefetch-and-priorities-in-chrome-776165961bbf),
98 | and a list of common `as` values can be
99 | [found on MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Preloading_content#What_types_of_content_can_be_preloaded).
100 |
101 | By default, the plugin will assume async script chunks will be preloaded. This is the equivalent of:
102 |
103 | ```js
104 | plugins: [
105 | new HtmlWebpackPlugin(),
106 | new PreloadWebpackPlugin({
107 | rel: 'preload',
108 | include: 'asyncChunks'
109 | })
110 | ]
111 | ```
112 |
113 | For a project generating two async scripts with dynamically generated names, such as
114 | `chunk.31132ae6680e598f8879.js` and `chunk.d15e7fdfc91b34bb78c4.js`, the following preloads
115 | will be injected into the document `
`:
116 |
117 | ```html
118 |
119 |
120 | ```
121 |
122 | You can also configure the plugin to preload all chunks (vendor, async, and normal chunks) using
123 | `include: 'allChunks'`, or only preload initial chunks with `include: 'initial'`.
124 |
125 | It is very common in webpack to use loaders such as `file-loader` to generate assets for specific
126 | types, such as fonts or images. If you wish to preload these files as well, even if they don't
127 | belong to a chunk, you can use `include: 'allAssets'`.
128 |
129 | ```js
130 | plugins: [
131 | new HtmlWebpackPlugin(),
132 | new PreloadWebpackPlugin({
133 | rel: 'preload',
134 | include: 'allChunks' // or 'initial', or 'allAssets'
135 | })
136 | ]
137 | ```
138 |
139 | In case you work with named chunks, you can explicitly specify which ones to `include` by passing an array:
140 |
141 | ```js
142 | plugins: [
143 | new HtmlWebpackPlugin(),
144 | new PreloadWebpackPlugin({
145 | rel: 'preload',
146 | include: ['home']
147 | })
148 | ]
149 | ```
150 |
151 | will inject just this:
152 |
153 | ```html
154 |
155 | ```
156 |
157 | ### Filtering chunks
158 |
159 | There may be chunks that you don't want to have preloaded (sourcemaps, for example). Before preloading each chunk, this plugin checks that the file does not match any regex in the `fileBlacklist` option. The default value of this blacklist is `[/\.map/]`, meaning no sourcemaps will be preloaded. You can easily override this:
160 |
161 | ```js
162 | new PreloadWebpackPlugin({
163 | fileBlacklist: [/\.whatever/]
164 | })
165 | ```
166 |
167 | Passing your own array will override the default, so if you want to continue filtering sourcemaps along with your own custom settings, you'll need to include the regex for sourcemaps:
168 |
169 | ```js
170 | new PreloadWebpackPlugin({
171 | fileBlacklist: [/\.map/, /\.whatever/]
172 | })
173 | ```
174 |
175 | ## Filtering HTML
176 |
177 | You may not want to preload resources in some of your HTML files. You can use `excludeHtmlNames` to
178 | tell this plugin to ignore one or more files.
179 |
180 | ```javascript
181 | plugins: [
182 | new HtmlWebpackPlugin({
183 | filename: 'index.html',
184 | template: 'src/index.html',
185 | chunks: ['main']
186 | }),
187 | new HtmlWebpackPlugin({
188 | filename: 'example.html',
189 | template: 'src/example.html',
190 | chunks: ['exampleEntry']
191 | }),
192 | // Only apply the plugin to index.html, not example.html.
193 | new PreloadWebpackPlugin({
194 | excludeHtmlNames: ['example.html'],
195 | })
196 | ```
197 |
198 | ### Resource hints
199 |
200 | Should you wish to use Resource Hints (such as `prefetch`) instead of `preload`, this plugin also supports wiring those up.
201 |
202 | Prefetch:
203 |
204 | ```js
205 | plugins: [
206 | new HtmlWebpackPlugin(),
207 | new PreloadWebpackPlugin({
208 | rel: 'prefetch'
209 | })
210 | ]
211 | ```
212 |
213 | For the async chunks mentioned earlier, the plugin would update your HTML to the following:
214 |
215 | ```html
216 |
217 |
218 | ```
219 |
220 | ## Including media
221 |
222 | `` elements have the ability to accept media attributes. These can accept media types or full-blown media queries, allowing you to do responsive preloading.
223 |
224 | You can pass the value for the media attribute in the `media` option:
225 |
226 | ```javascript
227 | plugins: [
228 | new HtmlWebpackPlugin(),
229 | new PreloadWebpackPlugin({
230 | rel: 'preload',
231 | media: '(min-width: 600px)'
232 | })
233 | ]
234 | ```
235 |
236 | ## Support
237 |
238 | If you've found an error or run into problems, please [file an issue](https://github.com/googlechrome/preload-webpack-plugin/issues).
239 |
240 | Patches are encouraged, and may be submitted by forking this project and
241 | submitting a pull request through GitHub.
242 |
243 | ## Contributing workflow
244 |
245 | [`src/index.js`](src/index.js) and [`src/lib/`](src/lib/) contains the primary source for the plugin.
246 | [`test/`](test/) contains tests.
247 |
248 | Test the plugin:
249 |
250 | ```sh
251 | $ npm install
252 | $ npm run test
253 | ```
254 |
255 | The project is written in ES2015, and is transpiled to support node 6 and above.
256 |
257 | ## Additional notes
258 |
259 | - Be careful not to `preload` resources a user is unlikely to need. This can waste their bandwidth.
260 | - Use `preload` for the current session if you think a user is likely to visit the next page. There is no
261 | 100% guarantee preloaded items will end up in the HTTP Cache and read locally beyond this session.
262 | - If optimizing for future sessions, use `prefetch` and `preconnect`. Prefetched resources are maintained
263 | in the HTTP Cache for at least 5 minutes (in Chrome) regardless of the resource's cachability.
264 |
265 | ## Alternative tools
266 |
267 | - webpack's native support:
268 | As of the [v4.6.0 release](https://github.com/webpack/webpack/releases/tag/v4.6.0)
269 | of webpack, there is native support for generating both prefetch and preload ``s via ["magic" comments in your `import()` statements](https://medium.com/webpack/link-rel-prefetch-preload-in-webpack-51a52358f84c).
270 |
271 | - [script-ext-html-webpack-plugin](https://github.com/numical/script-ext-html-webpack-plugin):
272 | Enhances `html-webpack-plugin` with options including 'async', 'defer', 'module' and 'preload'.
273 | As of [v1.7.0](https://github.com/numical/script-ext-html-webpack-plugin/pull/9#issuecomment-278239875),
274 | it supports async chunks.
275 |
276 | - [resource-hints-webpack-plugin](https://github.com/jantimon/resource-hints-webpack-plugin):
277 | Automatically wires resource hints for your resources. This plugin does does not currently
278 | support async chunks.
279 |
280 | ## License
281 |
282 | Copyright 2019 Google, Inc.
283 |
284 | Licensed to the Apache Software Foundation (ASF) under one or more contributor
285 | license agreements. See the NOTICE file distributed with this work for
286 | additional information regarding copyright ownership. The ASF licenses this
287 | file to you under the Apache License, Version 2.0 (the "License"); you may not
288 | use this file except in compliance with the License. You may obtain a copy of
289 | the License at
290 |
291 | http://www.apache.org/licenses/LICENSE-2.0
292 |
293 | Unless required by applicable law or agreed to in writing, software
294 | distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
295 | WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
296 | License for the specific language governing permissions and limitations under
297 | the License.
298 |
299 | [npm-url]: https://npmjs.org/package/preload-webpack-plugin
300 | [npm-img]: https://badge.fury.io/js/preload-webpack-plugin.svg
301 | [npm-downloads-img]: https://img.shields.io/npm/dm/preload-webpack-plugin.svg?style=flat-square
302 | [daviddm-img]: https://david-dm.org/googlechromelabs/preload-webpack-plugin.svg
303 | [daviddm-url]: https://david-dm.org/googlechromelabs/preload-webpack-plugin
304 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "preload-webpack-plugin",
3 | "version": "3.0.0",
4 | "description": "A webpack plugin for injecting into HtmlWebpackPlugin pages, with async chunk support",
5 | "author": "Addy Osmani (https://github.com/addyosmani)",
6 | "license": "Apache-2.0",
7 | "bugs": {
8 | "url": "https://github.com/googlechromelabs/preload-webpack-plugin/issues"
9 | },
10 | "homepage": "https://github.com/googlechromelabs/preload-webpack-plugin",
11 | "repository": {
12 | "type": "git",
13 | "url": "https://github.com/googlechromelabs/preload-webpack-plugin.git"
14 | },
15 | "keywords": [
16 | "webpack",
17 | "plugin",
18 | "html-webpack-plugin",
19 | "script",
20 | "preload"
21 | ],
22 | "engines": {
23 | "node": ">=8.0.0"
24 | },
25 | "scripts": {
26 | "lint": "eslint --format=codeframe .",
27 | "test": "jasmine test/unit/* test/webpack*/index.js",
28 | "coverage": "nyc npm run test",
29 | "clean": "rimraf build",
30 | "build": "npm run clean && babel --out-dir=build src",
31 | "publish-stable": "npm run lint && npm run test && npm run build && npm publish",
32 | "publish-next": "npm run lint && npm run test && npm run build && npm publish --tag next"
33 | },
34 | "main": "build/index.js",
35 | "files": [
36 | "build"
37 | ],
38 | "devDependencies": {
39 | "@babel/cli": "^7.5.5",
40 | "@babel/core": "^7.5.5",
41 | "@babel/preset-env": "^7.5.5",
42 | "eslint": "^6.2.1",
43 | "eslint-config-google": "^0.13.0",
44 | "jasmine": "^3.4.0",
45 | "jsdom": "^15.1.1",
46 | "memory-fs": "^0.4.1",
47 | "nyc": "^14.1.1",
48 | "rimraf": "^3.0.0"
49 | },
50 | "peerDependencies": {
51 | "html-webpack-plugin": ">=3.0.0",
52 | "webpack": ">=4.0.0"
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/src/index.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @license
3 | * Copyright 2019 Google Inc.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | const assert = require('assert');
19 |
20 | const createHTMLElementString = require('./lib/create-html-element-string');
21 | const defaultOptions = require('./lib/default-options');
22 | const determineAsValue = require('./lib/determine-as-value');
23 | const extractChunks = require('./lib/extract-chunks');
24 | const insertLinksIntoHead = require('./lib/insert-links-into-head');
25 |
26 | class PreloadPlugin {
27 | constructor(options) {
28 | this.options = Object.assign({}, defaultOptions, options);
29 | }
30 |
31 | addLinks(compilation, htmlPluginData) {
32 | const options = this.options;
33 |
34 | // Bail out early if we're configured to exclude this HTML file.
35 | if (options.excludeHtmlNames.includes(htmlPluginData.plugin.options.filename)) {
36 | return htmlPluginData;
37 | }
38 |
39 | const extractedChunks = extractChunks({
40 | compilation,
41 | optionsInclude: options.include,
42 | });
43 |
44 | // Flatten the list of files.
45 | const allFiles = extractedChunks.reduce((accumulated, chunk) => {
46 | return accumulated.concat(chunk.files);
47 | }, []);
48 | const uniqueFiles = new Set(allFiles);
49 | const filteredFiles = [...uniqueFiles].filter(file => {
50 | return (
51 | !this.options.fileWhitelist ||
52 | this.options.fileWhitelist.some(regex => regex.test(file))
53 | );
54 | }).filter(file => {
55 | return (
56 | !this.options.fileBlacklist ||
57 | this.options.fileBlacklist.every(regex => !regex.test(file))
58 | );
59 | });
60 | // Sort to ensure the output is predictable.
61 | const sortedFilteredFiles = filteredFiles.sort();
62 |
63 | const links = [];
64 | const publicPath = compilation.outputOptions.publicPath || '';
65 | for (const file of sortedFilteredFiles) {
66 | const href = `${publicPath}${file}`;
67 |
68 | const attributes = {
69 | href,
70 | rel: options.rel,
71 | };
72 |
73 | // See https://github.com/GoogleChromeLabs/preload-webpack-plugin/issues/69
74 | if (options.media) {
75 | attributes.media = options.media;
76 | }
77 |
78 | // If we're preloading this resource (as opposed to prefetching),
79 | // then we need to set the 'as' attribute correctly.
80 | if (options.rel === 'preload') {
81 | attributes.as = determineAsValue({
82 | href,
83 | optionsAs: options.as,
84 | });
85 |
86 | // On the off chance that we have an 'href' attribute with a
87 | // cross-origin URL, set crossOrigin on the to trigger CORS mode.
88 | // when preloading fonts. (Non-CORS fonts can't be used.)
89 | if (attributes.as === 'font') {
90 | attributes.crossorigin = 'anonymous';
91 | }
92 | }
93 |
94 | const linkElementString = createHTMLElementString({
95 | attributes,
96 | elementName: 'link',
97 | });
98 | links.push(linkElementString);
99 | }
100 |
101 | htmlPluginData.html = insertLinksIntoHead({
102 | links,
103 | html: htmlPluginData.html,
104 | });
105 |
106 | return htmlPluginData;
107 | }
108 |
109 | apply(compiler) {
110 | compiler.hooks.compilation.tap(
111 | this.constructor.name,
112 | compilation => {
113 | // This is set in html-webpack-plugin pre-v4.
114 | let hook = compilation.hooks.htmlWebpackPluginAfterHtmlProcessing;
115 |
116 | if (!hook) {
117 | const [HtmlWebpackPlugin] = compiler.options.plugins.filter(
118 | (plugin) => plugin.constructor.name === 'HtmlWebpackPlugin');
119 | assert(HtmlWebpackPlugin, 'Unable to find an instance of ' +
120 | 'HtmlWebpackPlugin in the current compilation.');
121 | hook = HtmlWebpackPlugin.constructor.getHooks(compilation).beforeEmit;
122 | }
123 |
124 | hook.tapAsync(
125 | this.constructor.name,
126 | (htmlPluginData, callback) => {
127 | try {
128 | callback(null, this.addLinks(compilation, htmlPluginData));
129 | } catch (error) {
130 | callback(error);
131 | }
132 | }
133 | );
134 | }
135 | );
136 | }
137 | }
138 |
139 | module.exports = PreloadPlugin;
140 |
--------------------------------------------------------------------------------
/src/lib/create-html-element-string.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @license
3 | * Copyright 2018 Google Inc.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | const assert = require('assert');
19 |
20 | function createHTMLElementString({elementName, attributes={}, closingTagRequired=false}) {
21 | assert(elementName, 'Please provide an element name.');
22 | assert(!(/\W/.test(elementName)), 'The element name contains invalid characters.');
23 |
24 | const attributeStrings = [];
25 | for (const [attributeName, attributeValue] of Object.entries(attributes).sort()) {
26 | if (attributeValue === '') {
27 | attributeStrings.push(attributeName);
28 | } else {
29 | attributeStrings.push(`${attributeName}=${JSON.stringify(attributeValue)}`);
30 | }
31 | }
32 |
33 | let elementString = `<${elementName}`;
34 |
35 | if (attributeStrings.length > 0) {
36 | elementString += ' ' + attributeStrings.join(' ');
37 | }
38 |
39 | elementString += '>';
40 |
41 | if (closingTagRequired) {
42 | elementString += `${elementName}>`;
43 | }
44 |
45 | return elementString;
46 | }
47 |
48 | module.exports = createHTMLElementString;
49 |
--------------------------------------------------------------------------------
/src/lib/default-options.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @license
3 | * Copyright 2018 Google Inc.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | const defaultOptions = {
19 | rel: 'preload',
20 | include: 'asyncChunks',
21 | excludeHtmlNames: [],
22 | fileBlacklist: [/\.map/]
23 | };
24 |
25 | module.exports = defaultOptions;
26 |
--------------------------------------------------------------------------------
/src/lib/determine-as-value.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @license
3 | * Copyright 2019 Google Inc.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | const assert = require('assert');
19 | const path = require('path');
20 | const {URL} = require('url');
21 |
22 | function determineAsValue({optionsAs, href}) {
23 | assert(href, `The 'href' parameter was not provided.`);
24 |
25 | switch (typeof optionsAs) {
26 | case 'string': {
27 | return optionsAs;
28 | }
29 |
30 | case 'function': {
31 | return optionsAs(href);
32 | }
33 |
34 | case 'undefined': {
35 | // If `as` value is not provided in option, dynamically determine the correct
36 | // value based on the suffix of filename.
37 |
38 | // We only care about the pathname, so just use any domain when constructing the URL.
39 | const url = new URL(href, 'https://example.com');
40 | const extension = path.extname(url.pathname);
41 |
42 | if (extension === '.css') {
43 | return 'style';
44 | }
45 |
46 | if (extension === '.woff2') {
47 | return 'font';
48 | }
49 |
50 | return 'script';
51 | }
52 |
53 | default:
54 | throw new Error(`The 'as' option isn't set to a recognized value: ${optionsAs}`);
55 | }
56 | }
57 |
58 | module.exports = determineAsValue;
59 |
--------------------------------------------------------------------------------
/src/lib/extract-chunks.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @license
3 | * Copyright 2018 Google Inc.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | function extractChunks({compilation, optionsInclude}) {
19 | try {
20 | // 'asyncChunks' are chunks intended for lazy/async loading usually generated as
21 | // part of code-splitting with import() or require.ensure(). By default, asyncChunks
22 | // get wired up using link rel=preload when using this plugin. This behavior can be
23 | // configured to preload all types of chunks or just prefetch chunks as needed.
24 | if (optionsInclude === undefined || optionsInclude === 'asyncChunks') {
25 | return compilation.chunks.filter(chunk => {
26 | if ('canBeInitial' in chunk) {
27 | return !chunk.canBeInitial();
28 | } else {
29 | return !chunk.isInitial();
30 | }
31 | });
32 | }
33 |
34 | if (optionsInclude === 'initial') {
35 | return compilation.chunks.filter(chunk => {
36 | if ('canBeInitial' in chunk) {
37 | return chunk.canBeInitial();
38 | } else {
39 | return chunk.isInitial();
40 | }
41 | });
42 | }
43 |
44 | if (optionsInclude === 'allChunks') {
45 | // Async chunks, vendor chunks, normal chunks.
46 | return compilation.chunks;
47 | }
48 |
49 | if (optionsInclude === 'allAssets') {
50 | // Every asset, regardless of which chunk it's in.
51 | // Wrap it in a single, "psuedo-chunk" return value.
52 | return [{files: Object.keys(compilation.assets)}];
53 | }
54 |
55 | if (Array.isArray(optionsInclude)) {
56 | // Keep only user specified chunks.
57 | return compilation.chunks.filter((chunk) => chunk.name && optionsInclude.includes(chunk.name));
58 | }
59 | } catch (error) {
60 | return compilation.chunks;
61 | }
62 |
63 | throw new Error(`The 'include' option isn't set to a recognized value: ${optionsInclude}`);
64 | }
65 |
66 | module.exports = extractChunks;
67 |
--------------------------------------------------------------------------------
/src/lib/insert-links-into-head.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @license
3 | * Copyright 2018 Google Inc.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | function insertLinksIntoHead({html, links=[]}) {
19 | if (links.length === 0) {
20 | return html;
21 | }
22 |
23 | if (html.includes('')) {
24 | // If a valid closing is found, insert the new s right before it.
25 | return html.replace('', links.join('') + '');
26 | }
27 |
28 | if (html.includes('')) {
29 | // If there's a but no , create a containing the .
30 | return html.replace('', `${links.join('')}\n`);
31 | }
32 |
33 | throw new Error(`The HTML provided did not contain a or a :\n\n${html}`);
34 | }
35 |
36 | module.exports = insertLinksIntoHead;
37 |
--------------------------------------------------------------------------------
/test/.eslintrc.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | env: {
3 | jasmine: true,
4 | },
5 | };
6 |
--------------------------------------------------------------------------------
/test/fixtures/file.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @license
3 | * Copyright 2017 Google Inc.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 | console.log('lol');
18 | require.ensure(["./home.js"], function() {
19 | // var a = require("module-a");
20 | // console.log(a);
21 | }, 'home');
22 |
--------------------------------------------------------------------------------
/test/fixtures/font.woff2:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GoogleChromeLabs/preload-webpack-plugin/d55548cb25a385c0318ca526200877b062ab6e76/test/fixtures/font.woff2
--------------------------------------------------------------------------------
/test/fixtures/home.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @license
3 | * Copyright 2017 Google Inc.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 | console.log('home');
--------------------------------------------------------------------------------
/test/fixtures/load-css.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @license
3 | * Copyright 2017 Google Inc.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 | console.log('lol');
18 | console.log(require('./style.css'));
19 | require.ensure(["./home.js"], function() {
20 | // var a = require("module-a");
21 | // console.log(a);
22 | }, 'home');
23 |
--------------------------------------------------------------------------------
/test/fixtures/module-a.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @license
3 | * Copyright 2017 Google Inc.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 | console.log('module-a');
--------------------------------------------------------------------------------
/test/fixtures/style.css:
--------------------------------------------------------------------------------
1 | @font-face {
2 | font-family: test;
3 | src: url(./font.woff2);
4 | }
--------------------------------------------------------------------------------
/test/fixtures/vendor.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @license
3 | * Copyright 2017 Google Inc.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 | console.log('vendor');
--------------------------------------------------------------------------------
/test/spec.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @license
3 | * Copyright 2019 Google Inc.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | const MemoryFileSystem = require('memory-fs');
19 | const path = require('path');
20 | const {JSDOM} = require('jsdom');
21 |
22 | const PreloadPlugin = require('../src/index');
23 |
24 | const OUTPUT_DIR = path.join(__dirname, 'dist');
25 |
26 | module.exports = ({descriptionPrefix, webpack, HtmlWebpackPlugin}) => {
27 | describe(`${descriptionPrefix} When passed async chunks, it`, function() {
28 | it('should add preload tags', function(done) {
29 | const compiler = webpack({
30 | entry: {
31 | js: path.join(__dirname, 'fixtures', 'file.js')
32 | },
33 | output: {
34 | path: OUTPUT_DIR,
35 | filename: 'bundle.js',
36 | chunkFilename: 'chunk.[chunkhash].js',
37 | publicPath: '/',
38 | },
39 | plugins: [
40 | new HtmlWebpackPlugin(),
41 | new PreloadPlugin()
42 | ]
43 | }, function(err, result) {
44 | expect(err).toBeFalsy(err);
45 | expect(result.compilation.errors.length).toBe(0,
46 | result.compilation.errors.join('\n=========\n'));
47 |
48 | const html = result.compilation.assets['index.html'].source();
49 | const dom = new JSDOM(html);
50 |
51 | const links = dom.window.document.head.querySelectorAll('link');
52 | expect(links.length).toBe(1);
53 | expect(links[0].getAttribute('rel')).toBe('preload');
54 | expect(links[0].getAttribute('as')).toBe('script');
55 | expect(links[0].getAttribute('href')).toMatch(new RegExp('^/chunk\\.'));
56 |
57 | done();
58 | });
59 |
60 | compiler.outputFileSystem = new MemoryFileSystem();
61 | });
62 |
63 | it('should add prefetch tags', function(done) {
64 | const compiler = webpack({
65 | entry: {
66 | js: path.join(__dirname, 'fixtures', 'file.js')
67 | },
68 | output: {
69 | path: OUTPUT_DIR,
70 | filename: 'bundle.js',
71 | chunkFilename: 'chunk.[chunkhash].js',
72 | publicPath: '/',
73 | },
74 | plugins: [
75 | new HtmlWebpackPlugin(),
76 | new PreloadPlugin({
77 | rel: 'prefetch'
78 | })
79 | ]
80 | }, function(err, result) {
81 | expect(err).toBeFalsy(err);
82 | expect(result.compilation.errors.length).toBe(0,
83 | result.compilation.errors.join('\n=========\n'));
84 |
85 | const html = result.compilation.assets['index.html'].source();
86 | const dom = new JSDOM(html);
87 |
88 | const links = dom.window.document.head.querySelectorAll('link');
89 | expect(links.length).toBe(1);
90 | expect(links[0].getAttribute('rel')).toBe('prefetch');
91 | expect(links[0].getAttribute('href')).toMatch(new RegExp('^/chunk\\.'));
92 |
93 | done();
94 | });
95 | compiler.outputFileSystem = new MemoryFileSystem();
96 | });
97 |
98 | it('should respect publicPath', function(done) {
99 | const compiler = webpack({
100 | entry: {
101 | js: path.join(__dirname, 'fixtures', 'file.js')
102 | },
103 | output: {
104 | path: OUTPUT_DIR,
105 | filename: 'bundle.js',
106 | chunkFilename: 'chunk.[chunkhash].js',
107 | publicPath: 'https://example.com/',
108 | },
109 | plugins: [
110 | new HtmlWebpackPlugin(),
111 | new PreloadPlugin()
112 | ]
113 | }, function(err, result) {
114 | expect(err).toBeFalsy(err);
115 | expect(result.compilation.errors.length).toBe(0,
116 | result.compilation.errors.join('\n=========\n'));
117 |
118 | const html = result.compilation.assets['index.html'].source();
119 | const dom = new JSDOM(html);
120 |
121 | const links = dom.window.document.head.querySelectorAll('link');
122 | expect(links.length).toBe(1);
123 | expect(links[0].getAttribute('rel')).toBe('preload');
124 | expect(links[0].getAttribute('href')).toMatch(new RegExp('^https://example\\.com/chunk\\.'));
125 |
126 | done();
127 | });
128 | compiler.outputFileSystem = new MemoryFileSystem();
129 | });
130 | });
131 |
132 |
133 | describe(`${descriptionPrefix} When passed non-async chunks, it`, function() {
134 | it('should add preload tags', function(done) {
135 | const compiler = webpack({
136 | entry: path.join(__dirname, 'fixtures', 'file.js'),
137 | output: {
138 | path: OUTPUT_DIR,
139 | filename: 'bundle.js',
140 | chunkFilename: 'chunk.[chunkhash].js',
141 | publicPath: '/',
142 | },
143 | plugins: [
144 | new HtmlWebpackPlugin(),
145 | new PreloadPlugin({
146 | rel: 'preload',
147 | as: 'script',
148 | include: 'allChunks'
149 | })
150 | ]
151 | }, function(err, result) {
152 | expect(err).toBeFalsy(err);
153 | expect(result.compilation.errors.length).toBe(0,
154 | result.compilation.errors.join('\n=========\n'));
155 |
156 | const html = result.compilation.assets['index.html'].source();
157 | const dom = new JSDOM(html);
158 |
159 | const links = dom.window.document.head.querySelectorAll('link');
160 | expect(links.length).toBe(2);
161 | expect(links[0].getAttribute('rel')).toBe('preload');
162 | expect(links[0].getAttribute('as')).toBe('script');
163 | expect(links[0].getAttribute('href')).toBe('/bundle.js');
164 | expect(links[1].getAttribute('rel')).toBe('preload');
165 | expect(links[1].getAttribute('as')).toBe('script');
166 | expect(links[1].getAttribute('href')).toMatch(new RegExp('^/chunk\\.'));
167 |
168 | done();
169 | });
170 | compiler.outputFileSystem = new MemoryFileSystem();
171 | });
172 |
173 | it('should set as="style" for CSS, and as="script" otherwise', function(done) {
174 | const compiler = webpack({
175 | entry: {
176 | js: path.join(__dirname, 'fixtures', 'file.js')
177 | },
178 | output: {
179 | path: OUTPUT_DIR,
180 | filename: 'bundle.js',
181 | chunkFilename: 'chunk.[chunkhash].css',
182 | publicPath: '/',
183 | },
184 | plugins: [
185 | new HtmlWebpackPlugin(),
186 | new PreloadPlugin({
187 | rel: 'preload',
188 | include: 'allChunks'
189 | })
190 | ]
191 | }, function(err, result) {
192 | expect(err).toBeFalsy(err);
193 | expect(result.compilation.errors.length).toBe(0,
194 | result.compilation.errors.join('\n=========\n'));
195 |
196 | const html = result.compilation.assets['index.html'].source();
197 | const dom = new JSDOM(html);
198 |
199 | const links = dom.window.document.head.querySelectorAll('link');
200 | expect(links.length).toBe(2);
201 | expect(links[0].getAttribute('rel')).toBe('preload');
202 | expect(links[0].getAttribute('as')).toBe('script');
203 | expect(links[0].getAttribute('href')).toBe('/bundle.js');
204 | expect(links[1].getAttribute('rel')).toBe('preload');
205 | expect(links[1].getAttribute('as')).toBe('style');
206 | expect(links[1].getAttribute('href')).toMatch(new RegExp('^/chunk\\.'));
207 |
208 | done();
209 | });
210 | compiler.outputFileSystem = new MemoryFileSystem();
211 | });
212 |
213 |
214 | it('should use the value for the as attribute passed in the configuration', (done) => {
215 | const compiler = webpack({
216 | entry: path.join(__dirname, 'fixtures', 'file.js'),
217 | output: {
218 | path: OUTPUT_DIR,
219 | filename: 'bundle.js',
220 | chunkFilename: 'chunk.[chunkhash].css',
221 | publicPath: '/',
222 | },
223 | plugins: [
224 | new HtmlWebpackPlugin(),
225 | new PreloadPlugin({
226 | rel: 'preload',
227 | as: 'testing',
228 | include: 'allChunks'
229 | })
230 | ]
231 | }, function(err, result) {
232 | expect(err).toBeFalsy(err);
233 | expect(result.compilation.errors.length).toBe(0,
234 | result.compilation.errors.join('\n=========\n'));
235 |
236 | const html = result.compilation.assets['index.html'].source();
237 | const dom = new JSDOM(html);
238 |
239 | const links = dom.window.document.head.querySelectorAll('link');
240 | expect(links.length).toBe(2);
241 | expect(links[0].getAttribute('rel')).toBe('preload');
242 | expect(links[0].getAttribute('as')).toBe('testing');
243 | expect(links[0].getAttribute('href')).toBe('/bundle.js');
244 | expect(links[1].getAttribute('rel')).toBe('preload');
245 | expect(links[1].getAttribute('as')).toBe('testing');
246 | expect(links[1].getAttribute('href')).toMatch(new RegExp('^/chunk\\.'));
247 |
248 | done();
249 | });
250 | compiler.outputFileSystem = new MemoryFileSystem();
251 | });
252 |
253 | it('should set as="font" and crossOrigin for .woff2 assets', (done) => {
254 | const compiler = webpack({
255 | entry: {
256 | js: path.join(__dirname, 'fixtures', 'file.js')
257 | },
258 | output: {
259 | path: OUTPUT_DIR,
260 | filename: 'bundle.js',
261 | chunkFilename: 'chunk.[chunkhash].woff2',
262 | publicPath: '/',
263 | },
264 | plugins: [
265 | new HtmlWebpackPlugin(),
266 | new PreloadPlugin({
267 | rel: 'preload',
268 | include: 'allChunks'
269 | })
270 | ]
271 | }, function(err, result) {
272 | expect(err).toBeFalsy(err);
273 | expect(result.compilation.errors.length).toBe(0,
274 | result.compilation.errors.join('\n=========\n'));
275 |
276 | const html = result.compilation.assets['index.html'].source();
277 | const dom = new JSDOM(html);
278 |
279 | const links = dom.window.document.head.querySelectorAll('link');
280 | expect(links.length).toBe(2);
281 | expect(links[0].getAttribute('rel')).toBe('preload');
282 | expect(links[0].getAttribute('as')).toBe('script');
283 | expect(links[0].getAttribute('href')).toBe('/bundle.js');
284 | expect(links[1].getAttribute('rel')).toBe('preload');
285 | expect(links[1].getAttribute('as')).toBe('font');
286 | expect(links[1].hasAttribute('crossorigin')).toBeTruthy();
287 | expect(links[1].getAttribute('href')).toMatch(new RegExp('^/chunk\\.'));
288 |
289 | done();
290 | });
291 | compiler.outputFileSystem = new MemoryFileSystem();
292 | });
293 |
294 | it('should allow setting the as value via a callback', function(done) {
295 | const compiler = webpack({
296 | entry: path.join(__dirname, 'fixtures', 'file.js'),
297 | output: {
298 | path: OUTPUT_DIR,
299 | filename: 'bundle.js',
300 | chunkFilename: 'chunk.[chunkhash].css',
301 | publicPath: '/',
302 | },
303 | plugins: [
304 | new HtmlWebpackPlugin(),
305 | new PreloadPlugin({
306 | rel: 'preload',
307 | as: (href) => href.startsWith('/chunk') ? 'test2' : 'test1',
308 | include: 'allChunks',
309 | }),
310 | ],
311 | }, function(err, result) {
312 | expect(err).toBeFalsy(err);
313 | expect(result.compilation.errors.length).toBe(0,
314 | result.compilation.errors.join('\n=========\n'));
315 |
316 | const html = result.compilation.assets['index.html'].source();
317 | const dom = new JSDOM(html);
318 |
319 | const links = dom.window.document.head.querySelectorAll('link');
320 | expect(links.length).toBe(2);
321 | expect(links[0].getAttribute('rel')).toBe('preload');
322 | expect(links[0].getAttribute('as')).toBe('test1');
323 | expect(links[0].getAttribute('href')).toBe('/bundle.js');
324 | expect(links[1].getAttribute('rel')).toBe('preload');
325 | expect(links[1].getAttribute('as')).toBe('test2');
326 | expect(links[1].getAttribute('href')).toMatch(new RegExp('^/chunk\\.'));
327 |
328 | done();
329 | });
330 | compiler.outputFileSystem = new MemoryFileSystem();
331 | });
332 |
333 | it('should use the value for the media attribute passed in the configuration', (done) => {
334 | const compiler = webpack({
335 | entry: path.join(__dirname, 'fixtures', 'file.js'),
336 | output: {
337 | path: OUTPUT_DIR,
338 | filename: 'bundle.js',
339 | chunkFilename: 'chunk.[chunkhash].css',
340 | publicPath: '/',
341 | },
342 | plugins: [
343 | new HtmlWebpackPlugin(),
344 | new PreloadPlugin({
345 | rel: 'preload',
346 | media: '(min-width: 600px)',
347 | include: 'allChunks'
348 | }),
349 | ]
350 | }, function(err, result) {
351 | expect(err).toBeFalsy(err);
352 | expect(result.compilation.errors.length).toBe(0,
353 | result.compilation.errors.join('\n=========\n'));
354 |
355 | const html = result.compilation.assets['index.html'].source();
356 | const dom = new JSDOM(html);
357 |
358 | const links = dom.window.document.head.querySelectorAll('link');
359 | expect(links.length).toBe(2);
360 | expect(links[0].getAttribute('rel')).toBe('preload');
361 | expect(links[0].getAttribute('media')).toBe('(min-width: 600px)');
362 | expect(links[0].getAttribute('href')).toBe('/bundle.js');
363 | expect(links[1].getAttribute('rel')).toBe('preload');
364 | expect(links[1].getAttribute('media')).toBe('(min-width: 600px)');
365 | expect(links[1].getAttribute('href')).toMatch(new RegExp('^/chunk\\.'));
366 |
367 | done();
368 | });
369 | compiler.outputFileSystem = new MemoryFileSystem();
370 | });
371 | });
372 |
373 | describe(`${descriptionPrefix} When passed normal chunks, it`, function() {
374 | it('should add prefetch links', function(done) {
375 | const compiler = webpack({
376 | entry: path.join(__dirname, 'fixtures', 'file.js'),
377 | output: {
378 | path: OUTPUT_DIR
379 | },
380 | plugins: [
381 | new HtmlWebpackPlugin(),
382 | new PreloadPlugin({
383 | rel: 'prefetch',
384 | include: 'allChunks'
385 | })
386 | ]
387 | }, function(err, result) {
388 | expect(err).toBeFalsy(err);
389 | expect(result.compilation.errors.length).toBe(0,
390 | result.compilation.errors.join('\n=========\n'));
391 |
392 | const html = result.compilation.assets['index.html'].source();
393 | const dom = new JSDOM(html);
394 |
395 | const links = dom.window.document.head.querySelectorAll('link');
396 | expect(links.length).toBe(2);
397 | expect(links[0].getAttribute('rel')).toBe('prefetch');
398 | expect(links[0].hasAttribute('as')).toBeFalsy();
399 | expect(links[0].getAttribute('href')).toBe('home.js');
400 | expect(links[1].getAttribute('rel')).toBe('prefetch');
401 | expect(links[1].hasAttribute('as')).toBeFalsy();
402 | expect(links[1].getAttribute('href')).toBe('main.js');
403 |
404 | done();
405 | });
406 | compiler.outputFileSystem = new MemoryFileSystem();
407 | });
408 | });
409 |
410 | describe(`${descriptionPrefix} When using 'include', it`, function() {
411 | it('should filter based on chunkname', function(done) {
412 | const compiler = webpack({
413 | entry: path.join(__dirname, 'fixtures', 'file.js'),
414 | output: {
415 | path: OUTPUT_DIR,
416 | filename: 'bundle.js',
417 | chunkFilename: '[name].[chunkhash].js',
418 | publicPath: '/',
419 | },
420 | plugins: [
421 | new HtmlWebpackPlugin(),
422 | new PreloadPlugin({
423 | rel: 'preload',
424 | as: 'script',
425 | include: ['home']
426 | })
427 | ]
428 | }, function(err, result) {
429 | expect(err).toBeFalsy(err);
430 | expect(result.compilation.errors.length).toBe(0,
431 | result.compilation.errors.join('\n=========\n'));
432 |
433 | const html = result.compilation.assets['index.html'].source();
434 | const dom = new JSDOM(html);
435 |
436 | const links = dom.window.document.head.querySelectorAll('link');
437 | expect(links.length).toBe(1);
438 | expect(links[0].getAttribute('rel')).toBe('preload');
439 | expect(links[0].getAttribute('as')).toBe('script');
440 | expect(links[0].getAttribute('href')).toMatch(new RegExp('^/home\\.'));
441 |
442 | done();
443 | });
444 | compiler.outputFileSystem = new MemoryFileSystem();
445 | });
446 |
447 | it('should filter based on chunkname, including the sourcemap', function(done) {
448 | const compiler = webpack({
449 | entry: path.join(__dirname, 'fixtures', 'file.js'),
450 | devtool: 'cheap-source-map',
451 | output: {
452 | path: OUTPUT_DIR,
453 | filename: 'bundle.js',
454 | chunkFilename: '[name].js',
455 | publicPath: '/',
456 | },
457 | plugins: [
458 | new HtmlWebpackPlugin(),
459 | new PreloadPlugin({
460 | rel: 'preload',
461 | as: 'script',
462 | include: ['home'],
463 | // Disable the default file blacklist.
464 | // This will cause the .map file to be included.
465 | fileBlacklist: [],
466 | })
467 | ]
468 | }, function(err, result) {
469 | expect(err).toBeFalsy(err);
470 | expect(result.compilation.errors.length).toBe(0,
471 | result.compilation.errors.join('\n=========\n'));
472 |
473 | const html = result.compilation.assets['index.html'].source();
474 | const dom = new JSDOM(html);
475 |
476 | const links = dom.window.document.head.querySelectorAll('link');
477 | expect(links.length).toBe(2);
478 | expect(links[0].getAttribute('rel')).toBe('preload');
479 | expect(links[0].getAttribute('as')).toBe('script');
480 | expect(links[0].getAttribute('href')).toBe('/home.js');
481 | expect(links[1].getAttribute('rel')).toBe('preload');
482 | expect(links[1].getAttribute('as')).toBe('script');
483 | expect(links[1].getAttribute('href')).toBe('/home.js.map');
484 |
485 | done();
486 | });
487 | compiler.outputFileSystem = new MemoryFileSystem();
488 | });
489 |
490 | // TODO: Is this testing the right thing? We might need a test around, e.g.,
491 | // using a different plugin that adds assets without also creating chunks.
492 | it(`should pull in additional assets when set to 'allAssets'`, function(done) {
493 | const compiler = webpack({
494 | entry: {
495 | theFirstEntry: path.join(__dirname, 'fixtures', 'file.js'),
496 | theSecondEntry: path.join(__dirname, 'fixtures', 'vendor.js'),
497 | },
498 | output: {
499 | path: OUTPUT_DIR,
500 | filename: '[name].js',
501 | },
502 | plugins: [
503 | new HtmlWebpackPlugin(),
504 | new PreloadPlugin({
505 | include: 'allAssets',
506 | }),
507 | ]
508 | }, function(err, result) {
509 | expect(err).toBeFalsy(err);
510 | expect(result.compilation.errors.length).toBe(0,
511 | result.compilation.errors.join('\n=========\n'));
512 |
513 | const html = result.compilation.assets['index.html'].source();
514 | const dom = new JSDOM(html);
515 |
516 | const links = dom.window.document.head.querySelectorAll('link');
517 | expect(links.length).toBe(3);
518 | expect(links[0].getAttribute('rel')).toBe('preload');
519 | expect(links[0].getAttribute('as')).toBe('script');
520 | expect(links[0].getAttribute('href')).toBe('home.js');
521 | expect(links[1].getAttribute('rel')).toBe('preload');
522 | expect(links[1].getAttribute('as')).toBe('script');
523 | expect(links[1].getAttribute('href')).toBe('theFirstEntry.js');
524 | expect(links[2].getAttribute('rel')).toBe('preload');
525 | expect(links[2].getAttribute('as')).toBe('script');
526 | expect(links[2].getAttribute('href')).toBe('theSecondEntry.js');
527 |
528 | done();
529 | });
530 | compiler.outputFileSystem = new MemoryFileSystem();
531 | });
532 |
533 | it(`should honor fileWhitelist and fileBlacklist, with the blacklist taking precedence`, function(done) {
534 | const compiler = webpack({
535 | entry: {
536 | theFirstEntry: path.join(__dirname, 'fixtures', 'file.js'),
537 | theSecondEntry: path.join(__dirname, 'fixtures', 'vendor.js'),
538 | },
539 | output: {
540 | path: OUTPUT_DIR,
541 | filename: '[name].js',
542 | },
543 | plugins: [
544 | new HtmlWebpackPlugin(),
545 | new PreloadPlugin({
546 | include: 'allAssets',
547 | fileWhitelist: [/Entry/],
548 | fileBlacklist: [/First/],
549 | }),
550 | ]
551 | }, function(err, result) {
552 | expect(err).toBeFalsy(err);
553 | expect(result.compilation.errors.length).toBe(0,
554 | result.compilation.errors.join('\n=========\n'));
555 |
556 | const html = result.compilation.assets['index.html'].source();
557 | const dom = new JSDOM(html);
558 |
559 | const links = dom.window.document.head.querySelectorAll('link');
560 | expect(links.length).toBe(1);
561 | expect(links[0].getAttribute('rel')).toBe('preload');
562 | expect(links[0].getAttribute('as')).toBe('script');
563 | expect(links[0].getAttribute('href')).toBe('theSecondEntry.js');
564 |
565 | done();
566 | });
567 | compiler.outputFileSystem = new MemoryFileSystem();
568 | });
569 | });
570 |
571 | describe(`${descriptionPrefix} When using an empty config, it`, function() {
572 | it('should not preload .map files', function(done) {
573 | const compiler = webpack({
574 | entry: {
575 | js: path.join(__dirname, 'fixtures', 'file.js')
576 | },
577 | output: {
578 | path: OUTPUT_DIR,
579 | filename: 'bundle.js',
580 | chunkFilename: 'chunk.[chunkhash].js',
581 | publicPath: '/',
582 | },
583 | devtool: 'cheap-source-map',
584 | plugins: [
585 | new HtmlWebpackPlugin(),
586 | new PreloadPlugin()
587 | ]
588 | }, function(err, result) {
589 | expect(err).toBeFalsy(err);
590 | expect(result.compilation.errors.length).toBe(0,
591 | result.compilation.errors.join('\n=========\n'));
592 |
593 | const html = result.compilation.assets['index.html'].source();
594 | const dom = new JSDOM(html);
595 |
596 | const links = dom.window.document.head.querySelectorAll('link');
597 | expect(links.length).toBe(1);
598 | expect(links[0].getAttribute('rel')).toBe('preload');
599 | expect(links[0].getAttribute('as')).toBe('script');
600 | expect(links[0].getAttribute('href')).toMatch(new RegExp('^/chunk\\.'));
601 |
602 | done();
603 | });
604 | compiler.outputFileSystem = new MemoryFileSystem();
605 | });
606 | });
607 |
608 | describe(`${descriptionPrefix} When excludeHtmlNames is used,`, function() {
609 | it(`should not modify the HTML of an asset that's listed`, function(done) {
610 | const compiler = webpack({
611 | entry: {
612 | js: path.join(__dirname, 'fixtures', 'file.js')
613 | },
614 | output: {
615 | path: OUTPUT_DIR,
616 | filename: 'bundle.js',
617 | chunkFilename: '[name].[chunkhash].js',
618 | publicPath: '/',
619 | },
620 | plugins: [
621 | new HtmlWebpackPlugin({
622 | filename: 'ignored.html',
623 | }),
624 | new PreloadPlugin({
625 | excludeHtmlNames: ['ignored.html'],
626 | })
627 | ]
628 | }, function(err, result) {
629 | expect(err).toBeFalsy(err);
630 | expect(result.compilation.errors.length).toBe(0,
631 | result.compilation.errors.join('\n=========\n'));
632 |
633 | const html = result.compilation.assets['ignored.html'].source();
634 | const dom = new JSDOM(html);
635 |
636 | const links = dom.window.document.head.querySelectorAll('link');
637 | expect(links.length).toBe(0);
638 |
639 | done();
640 | });
641 | compiler.outputFileSystem = new MemoryFileSystem();
642 | });
643 |
644 | it(`should not modify the HTML of an asset that's listed, but modify the HTML of the asset that isn't listed`, function(done) {
645 | const compiler = webpack({
646 | entry: {
647 | js: path.join(__dirname, 'fixtures', 'file.js')
648 | },
649 | output: {
650 | path: OUTPUT_DIR,
651 | filename: 'bundle.js',
652 | chunkFilename: '[name].[chunkhash].js',
653 | publicPath: '/',
654 | },
655 | plugins: [
656 | new HtmlWebpackPlugin({
657 | filename: 'ignored.html',
658 | }),
659 | new HtmlWebpackPlugin(),
660 | new PreloadPlugin({
661 | excludeHtmlNames: ['ignored.html'],
662 | })
663 | ]
664 | }, function(err, result) {
665 | expect(err).toBeFalsy(err);
666 | expect(result.compilation.errors.length).toBe(0,
667 | result.compilation.errors.join('\n=========\n'));
668 |
669 | const ignoredHtml = result.compilation.assets['ignored.html'].source();
670 | const ignoredDom = new JSDOM(ignoredHtml);
671 |
672 | const ignoredLinks = ignoredDom.window.document.head.querySelectorAll('link');
673 | expect(ignoredLinks.length).toBe(0);
674 |
675 | const html = result.compilation.assets['index.html'].source();
676 | const dom = new JSDOM(html);
677 |
678 | const links = dom.window.document.head.querySelectorAll('link');
679 | expect(links.length).toBe(1);
680 | expect(links[0].getAttribute('rel')).toBe('preload');
681 | expect(links[0].getAttribute('as')).toBe('script');
682 | expect(links[0].getAttribute('href')).toMatch(new RegExp('^/home\\.'));
683 |
684 | done();
685 | });
686 | compiler.outputFileSystem = new MemoryFileSystem();
687 | });
688 |
689 | it(`should modify the HTML of multiple assets that don't match the exclusion name`, function(done) {
690 | const compiler = webpack({
691 | entry: {
692 | js: path.join(__dirname, 'fixtures', 'file.js')
693 | },
694 | output: {
695 | path: OUTPUT_DIR,
696 | filename: 'bundle.js',
697 | chunkFilename: '[name].[chunkhash].js',
698 | publicPath: '/',
699 | },
700 | plugins: [
701 | new HtmlWebpackPlugin({
702 | filename: 'file1.html',
703 | }),
704 | new HtmlWebpackPlugin({
705 | filename: 'file2.html',
706 | }),
707 | new PreloadPlugin({
708 | excludeHtmlNames: ['does-not-match.html'],
709 | })
710 | ]
711 | }, function(err, result) {
712 | expect(err).toBeFalsy(err);
713 | expect(result.compilation.errors.length).toBe(0,
714 | result.compilation.errors.join('\n=========\n'));
715 |
716 | const html1 = result.compilation.assets['file1.html'].source();
717 | const dom1 = new JSDOM(html1);
718 |
719 | const links1 = dom1.window.document.head.querySelectorAll('link');
720 | expect(links1.length).toBe(1);
721 | expect(links1[0].getAttribute('rel')).toBe('preload');
722 | expect(links1[0].getAttribute('as')).toBe('script');
723 | expect(links1[0].getAttribute('href')).toMatch(new RegExp('^/home\\.'));
724 |
725 | const html2 = result.compilation.assets['file2.html'].source();
726 | const dom2 = new JSDOM(html2);
727 |
728 | const links2 = dom2.window.document.head.querySelectorAll('link');
729 | expect(links2.length).toBe(1);
730 | expect(links2[0].getAttribute('rel')).toBe('preload');
731 | expect(links2[0].getAttribute('as')).toBe('script');
732 | expect(links2[0].getAttribute('href')).toMatch(new RegExp('^/home\\.'));
733 |
734 | done();
735 | });
736 | compiler.outputFileSystem = new MemoryFileSystem();
737 | });
738 | });
739 | };
740 |
--------------------------------------------------------------------------------
/test/unit/create-html-element-string.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @license
3 | * Copyright 2018 Google Inc.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | const createHtmlElementString = require('../../src/lib/create-html-element-string');
19 |
20 | describe(`Error Conditions:`, function() {
21 | it(`should throw when called without an elementName`, function(done) {
22 | expect(
23 | () => createHtmlElementString({})
24 | ).toThrowError('Please provide an element name.');
25 |
26 | done();
27 | });
28 |
29 | it(`should throw when called with an elementName matching \\W`, function(done) {
30 | expect(
31 | () => createHtmlElementString({elementName: 'Testing!'})
32 | ).toThrowError('The element name contains invalid characters.');
33 |
34 | done();
35 | });
36 | });
37 |
38 | describe(`Defaults Tests:`, function() {
39 | it(`should support usage with just an elementName, and defaults for everything else`, function(done) {
40 | const elementString = createHtmlElementString({
41 | elementName: 'test',
42 | });
43 |
44 | expect(elementString).toEqual('');
45 |
46 | done();
47 | });
48 | });
49 |
50 | describe(`Attributes Tests:`, function() {
51 | it(`should support attributes without values`, function(done) {
52 | const elementString = createHtmlElementString({
53 | elementName: 'test',
54 | attributes: {
55 | one: '',
56 | two: '',
57 | }
58 | });
59 |
60 | expect(elementString).toEqual('');
61 |
62 | done();
63 | });
64 |
65 | it(`should support a mix of attributes with and without values`, function(done) {
66 | const elementString = createHtmlElementString({
67 | elementName: 'test',
68 | attributes: {
69 | one: '',
70 | two: '2'
71 | }
72 | });
73 |
74 | expect(elementString).toEqual('');
75 |
76 | done();
77 | });
78 |
79 | it(`should add the attributes sorted in alphanumeric order`, function(done) {
80 | const elementString = createHtmlElementString({
81 | elementName: 'test',
82 | attributes: {
83 | xyz: '3',
84 | abc: '1',
85 | def: '2'
86 | }
87 | });
88 |
89 | expect(elementString).toEqual('');
90 |
91 | done();
92 | });
93 |
94 | it(`should properly escape the attribute values as strings`, function(done) {
95 | const elementString = createHtmlElementString({
96 | elementName: 'test',
97 | attributes: {
98 | string: `Strings: '"\``
99 | }
100 | });
101 |
102 | expect(elementString).toEqual('');
103 |
104 | done();
105 | });
106 | });
107 |
108 | describe(`Closing Tag Tests:`, function() {
109 | it(`should add a closing tag when specified`, function(done) {
110 | const elementString = createHtmlElementString({
111 | elementName: 'test',
112 | closingTagRequired: true,
113 | });
114 |
115 | expect(elementString).toEqual('');
116 |
117 | done();
118 | });
119 | });
120 |
--------------------------------------------------------------------------------
/test/unit/determine-as-value.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @license
3 | * Copyright 2018 Google Inc.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | const determineAsValue = require('../../src/lib/determine-as-value');
19 |
20 | describe(`Error Conditions:`, function() {
21 | it(`should throw when called without an href value`, function(done) {
22 | expect(
23 | () => determineAsValue({optionsAs: 'ignored'})
24 | ).toThrowError(`The 'href' parameter was not provided.`);
25 |
26 | done();
27 | });
28 |
29 | it(`should throw when called with an invalid optionsAs value`, function(done) {
30 | expect(
31 | () => determineAsValue({href: '/', optionsAs: {}})
32 | ).toThrowError(`The 'as' option isn't set to a recognized value: [object Object]`);
33 |
34 | done();
35 | });
36 | });
37 |
38 | describe(`OptionsAs Tests:`, function() {
39 | it(`should support passing in a string`, function(done) {
40 | const asValue = determineAsValue({href: '/', optionsAs: 'test'});
41 |
42 | expect(asValue).toEqual('test');
43 |
44 | done();
45 | });
46 |
47 | it(`should support passing in a function`, function(done) {
48 | const asValue = determineAsValue({href: '/', optionsAs: (href) => href + 'test'});
49 |
50 | expect(asValue).toEqual('/test');
51 |
52 | done();
53 | });
54 |
55 | it(`should support passing in undefined, when href ends with .css`, function(done) {
56 | const asValue = determineAsValue({href: '/test.css'});
57 |
58 | expect(asValue).toEqual('style');
59 |
60 | done();
61 | });
62 |
63 | it(`should support passing in undefined, when href ends with .woff2`, function(done) {
64 | const asValue = determineAsValue({href: '/test.woff2'});
65 |
66 | expect(asValue).toEqual('font');
67 |
68 | done();
69 | });
70 |
71 | it(`should support passing in undefined, when href ends with .js`, function(done) {
72 | const asValue = determineAsValue({href: '/test.js'});
73 |
74 | expect(asValue).toEqual('script');
75 |
76 | done();
77 | });
78 |
79 | it(`should support passing in undefined, when href ends with anything else`, function(done) {
80 | const asValue = determineAsValue({href: '/test.ignored'});
81 |
82 | expect(asValue).toEqual('script');
83 |
84 | done();
85 | });
86 | });
87 |
--------------------------------------------------------------------------------
/test/unit/insert-links-into-head.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @license
3 | * Copyright 2018 Google Inc.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | const insertLinksIntoHead = require('../../src/lib/insert-links-into-head');
19 |
20 | describe(`Edge Conditions:`, function() {
21 | it(`should throw when called with HTML lacking a or `, function(done) {
22 | const html = '';
23 | expect(
24 | () => insertLinksIntoHead({html, links: ['']})
25 | ).toThrowError(`The HTML provided did not contain a or a :\n\n`);
26 |
27 | done();
28 | });
29 |
30 | it(`should return the HTML as-is when there are no links`, function(done) {
31 | const html = '';
32 | const updatedHtml = insertLinksIntoHead({html});
33 |
34 | expect(updatedHtml).toEqual(html);
35 |
36 | done();
37 | });
38 | });
39 |
40 | describe(`Normal Conditions:`, function() {
41 | it(`should support inserting a single link prior to the `, function(done) {
42 | const html = '';
43 | const updatedHtml = insertLinksIntoHead({
44 | html,
45 | links: [''],
46 | });
47 |
48 | expect(updatedHtml).toEqual(``);
49 |
50 | done();
51 | });
52 |
53 | it(`should support inserting multiple links prior to the `, function(done) {
54 | const html = '';
55 | const updatedHtml = insertLinksIntoHead({
56 | html,
57 | links: ['', ''],
58 | });
59 |
60 | expect(updatedHtml).toEqual(``);
61 |
62 | done();
63 | });
64 |
65 | it(`should support inserting a single link prior to the when there is no `, function(done) {
66 | const html = '';
67 | const updatedHtml = insertLinksIntoHead({
68 | html,
69 | links: [''],
70 | });
71 |
72 | expect(updatedHtml).toEqual(`\n`);
73 |
74 | done();
75 | });
76 |
77 | it(`should support inserting multiple links prior to the when there is no `, function(done) {
78 | const html = '';
79 | const updatedHtml = insertLinksIntoHead({
80 | html,
81 | links: ['', ''],
82 | });
83 |
84 | expect(updatedHtml).toEqual(`\n`);
85 |
86 | done();
87 | });
88 | });
89 |
--------------------------------------------------------------------------------
/test/webpack4-htmlplugin4/index.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @license
3 | * Copyright 2018 Google Inc.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | const webpack = require('webpack');
19 | const HtmlWebpackPlugin = require('html-webpack-plugin');
20 |
21 | const testSpec = require('../spec');
22 |
23 | const descriptionPrefix = '[webpack 4 / html-webpack-plugin 4]';
24 | testSpec({webpack, HtmlWebpackPlugin, descriptionPrefix});
25 |
--------------------------------------------------------------------------------
/test/webpack4-htmlplugin4/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "webpack4-htmlplugin4-tests",
3 | "version": "1.0.0",
4 | "description": "Test environment needed for webpack 4 and the html-webpack-plugin 4.",
5 | "main": "index.js",
6 | "author": "",
7 | "license": "Apache-2.0",
8 | "devDependencies": {
9 | "html-webpack-plugin": "^4.0.0-beta.8",
10 | "webpack": "^4.39.2"
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/test/webpack4/index.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @license
3 | * Copyright 2018 Google Inc.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | const webpack = require('webpack');
19 | const HtmlWebpackPlugin = require('html-webpack-plugin');
20 |
21 | const testSpec = require('../spec');
22 |
23 | const descriptionPrefix = '[webpack 4 / html-webpack-plugin 3]';
24 | testSpec({webpack, HtmlWebpackPlugin, descriptionPrefix});
25 |
--------------------------------------------------------------------------------
/test/webpack4/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "webpack4-tests",
3 | "version": "1.0.0",
4 | "description": "Test environment needed for webpack 4.",
5 | "main": "index.js",
6 | "author": "",
7 | "license": "Apache-2.0",
8 | "devDependencies": {
9 | "html-webpack-plugin": "^3.2.0",
10 | "webpack": "^4.39.2"
11 | }
12 | }
13 |
--------------------------------------------------------------------------------