├── .gitignore ├── test ├── samples │ ├── basic.js │ └── a.js └── test.js ├── CHANGELOG.md ├── index.d.ts ├── LICENSE ├── package.json ├── index.js └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | test/index.html 2 | -------------------------------------------------------------------------------- /test/samples/basic.js: -------------------------------------------------------------------------------- 1 | import('./a.js'); 2 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## v2.0.0 2 | 3 | Requires Node >= 14 4 | -------------------------------------------------------------------------------- /test/samples/a.js: -------------------------------------------------------------------------------- 1 | customElements.define('side-effect', class SideEffect extends HTMLElement { 2 | // hi 3 | }); 4 | -------------------------------------------------------------------------------- /index.d.ts: -------------------------------------------------------------------------------- 1 | import { OutputOptions, OutputBundle, RenderedChunk } from 'rollup' 2 | 3 | type SyncOrAsyncPredicate = (chunk: RenderedChunk & { code: string, map: any }) => Boolean | Promise 4 | 5 | interface Options { 6 | index: string; 7 | prefix?: string; 8 | shouldPreload?: SyncOrAsyncPredicate 9 | } 10 | 11 | export default function modulepreload(options: Options): { 12 | name: 'modulepreload', 13 | generateBundle: (outputOptions: OutputOptions, bundle: OutputBundle) => void 14 | } 15 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Benny Powers 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "rollup-plugin-modulepreload", 3 | "version": "2.0.0", 4 | "description": "Rollup plugin to add modulepreload links from generated chunks.", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "tape -r esm test/test.js" 8 | }, 9 | "repository": { 10 | "type": "git", 11 | "url": "git+https://github.com/bennypowers/rollup-plugin-modulepreload.git" 12 | }, 13 | "keywords": [ 14 | "rollup", 15 | "code splitting", 16 | "performance" 17 | ], 18 | "eslint": { 19 | "env": { 20 | "node": true 21 | } 22 | }, 23 | "author": "Benny Powers ", 24 | "license": "MIT", 25 | "bugs": { 26 | "url": "https://github.com/bennypowers/rollup-plugin-modulepreload/issues" 27 | }, 28 | "homepage": "https://github.com/bennypowers/rollup-plugin-modulepreload#readme", 29 | "dependencies": { 30 | "crocks": "^0.12.4", 31 | "fs.promises": "^0.1.2", 32 | "jsdom": "^16.4.0", 33 | "rollup-pluginutils": "^2.4.1" 34 | }, 35 | "devDependencies": { 36 | "esm": "^3.2.25", 37 | "mock-fs": "^4.13.0", 38 | "rollup": "^2.33.1", 39 | "tape": "^5.0.1" 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | require('fs.promises'); 2 | const { writeFile } = require('fs').promises; 3 | const { JSDOM } = require('jsdom'); 4 | const path = require('path'); 5 | const compose = require('crocks/helpers/compose') 6 | const curry = require('crocks/helpers/curry') 7 | const map = require('crocks/pointfree/map') 8 | 9 | const snd = ([, snd]) => snd; 10 | 11 | const getPath = ([x]) => x; 12 | 13 | const createLinkHref = prefix => path => `${prefix}/${path}` 14 | 15 | const createLinkElement = dom => path => { 16 | const link = dom.window.document.createElement('link'); 17 | link.rel = 'modulepreload'; 18 | link.href = path; 19 | return link; 20 | } 21 | 22 | const defaultShouldPreload = 23 | ({ exports, facadeModuleId, isDynamicEntry }) => 24 | !!( 25 | // preload dynamically imported chunks 26 | isDynamicEntry || 27 | // preload generated intermediate chunks 28 | (exports && exports.length && !facadeModuleId) 29 | ); 30 | 31 | const mapAsync = curry(f => xs => Promise.all(xs.map(f))); 32 | 33 | const filterAsync = curry(f => async xs => { 34 | const filterMap = await mapAsync(f, xs); 35 | return xs.filter((_, index) => filterMap[index]); 36 | }) 37 | 38 | const getPreloadChunks = async (shouldPreload, bundle) => await 39 | filterAsync(compose(shouldPreload, snd), Object.entries(bundle)) 40 | 41 | /** 42 | * Imports css as lit-element `css`-tagged constructible style sheets. 43 | * @param {Object} [options={}] 44 | * @return {Object} 45 | */ 46 | module.exports = function modulepreload({ index, prefix, shouldPreload = defaultShouldPreload } = {}) { 47 | return { 48 | name: 'modulepreload', 49 | 50 | async generateBundle({ format, dir }, bundle) { 51 | if (format !== 'es') return; 52 | const dom = await JSDOM.fromFile(index); 53 | 54 | const createLinkFromChunk = compose( 55 | createLinkElement(dom), 56 | createLinkHref(prefix ?? dir), 57 | getPath, 58 | ); 59 | 60 | const appendToDom = link => 61 | dom.window.document.head.appendChild(link); 62 | 63 | await getPreloadChunks(shouldPreload, bundle) 64 | .then(map(createLinkFromChunk)) 65 | .then(map(appendToDom)); 66 | 67 | await writeFile(path.resolve(index), dom.serialize(), 'utf-8') 68 | } 69 | }; 70 | } 71 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # rollup-plugin-modulepreload 2 | Rollup plugin to add [modulepreload links](https://html.spec.whatwg.org/multipage/links.html#link-type-modulepreload) from generated chunks. Users may customize which chunks are preloaded using the `shouldPreload` option. 3 | 4 | ## Usage 5 | 6 | ```js 7 | import config from './rollup.config.rest.js' 8 | import modulepreload from 'rollup-plugin-modulepreload'; 9 | 10 | export default { 11 | plugins: [ 12 | modulepreload({ 13 | prefix: 'modules', 14 | index: 'public/index.html', 15 | }) 16 | ] 17 | } 18 | ``` 19 | 20 | This will write something like the following to the `` of index.html 21 | ```html 22 | 23 | ``` 24 | 25 | ## Options 26 | 27 | |Name|Accepts|Default| 28 | |-----|-----|-----| 29 | |`index`|Path to index.html to modify.|`undefined`| 30 | |`prefix`|Path to prepend to chunk filenames in link tag `href` attribute.|your bundle's `dir` option| 31 | |`shouldPreload`|Predicate which takes a [`ChunkInfo`](https://rollupjs.org/guide/en#generatebundle)|[Default predicate](#default-predicate)| 32 | 33 | ### Determining Which Chunks to Preload 34 | You can customize the function which determines whether or not to preload a chunk by passing a `shouldPreload` predicate, which takes a [`ChunkInfo`](https://rollupjs.org/guide/en#generatebundle) object. 35 | 36 | It can be synchronous: 37 | ```js 38 | function shouldPreload({ code }) { 39 | return !!code && code.includes('INCLUDE THIS CHUNK'); 40 | } 41 | 42 | export default { 43 | input: 'src/index.js', 44 | plugins: [ 45 | modulepreload({ 46 | index: 'public/index.html', 47 | prefix: 'modules', 48 | shouldPreload, 49 | }) 50 | ] 51 | } 52 | ``` 53 | 54 | or asynchronous: 55 | ```js 56 | import { readFile } from 'fs/promises'; // node ^14 57 | 58 | async function shouldPreload(chunk) { 59 | if (!chunk.facadeModuleId) 60 | return false; 61 | 62 | const file = 63 | await readFile(chunk.facadeModuleId, 'utf-8'); 64 | 65 | return file.includes('INCLUDE THIS CHUNK'); 66 | } 67 | 68 | export default { 69 | input: 'src/index.js', 70 | plugins: [ 71 | modulepreload({ 72 | index: 'public/index.html', 73 | prefix: 'modules', 74 | shouldPreload, 75 | }) 76 | ] 77 | } 78 | ``` 79 | 80 | The Default Predicate is : 81 | ```js 82 | const defaultShouldPreload = 83 | ({ exports, facadeModuleId, isDynamicEntry }) => 84 | !!( 85 | // preload dynamically imported chunks 86 | isDynamicEntry || 87 | // preload generated intermediate chunks 88 | (exports && exports.length && !facadeModuleId) 89 | ); 90 | ``` 91 | -------------------------------------------------------------------------------- /test/test.js: -------------------------------------------------------------------------------- 1 | import test from 'tape'; 2 | import { rollup } from 'rollup'; 3 | import modulepreload from '../'; 4 | import { readFile, writeFile } from 'fs/promises'; 5 | 6 | const INDEX_SRC = 7 | ''; 8 | 9 | const PRELOADS_A = 10 | ''; 11 | 12 | test('writes modulepreload link to document head', async function(assert) { 13 | await writeFile(__dirname + '/index.html', INDEX_SRC, 'utf-8') 14 | 15 | const bundle = await rollup({ 16 | input: 'test/samples/basic.js', 17 | plugins: [modulepreload({ index: __dirname + '/index.html' })] 18 | }); 19 | 20 | await bundle.generate({ dir: 'output', format: 'es', }); 21 | 22 | const ACTUAL = 23 | await readFile(`${__dirname}/index.html`, 'utf-8'); 24 | 25 | assert.equal(ACTUAL, PRELOADS_A); 26 | 27 | assert.end(); 28 | }); 29 | 30 | test('writes modulepreload link with specified prefix', async function(assert) { 31 | await writeFile(__dirname + '/index.html', INDEX_SRC, 'utf-8') 32 | 33 | const bundle = await rollup({ 34 | input: 'test/samples/basic.js', 35 | plugins: [modulepreload({ index: __dirname + '/index.html' })] 36 | }); 37 | 38 | await bundle.generate({ dir: 'output', format: 'es', }); 39 | 40 | const ACTUAL = 41 | await readFile(`${__dirname}/index.html`, 'utf-8'); 42 | 43 | assert.equal(ACTUAL, PRELOADS_A); 44 | assert.end(); 45 | }); 46 | 47 | test('takes synchronous shouldPreload predicate', async function(assert) { 48 | await writeFile(__dirname + '/index.html', INDEX_SRC, 'utf-8') 49 | 50 | const bundle = await rollup({ 51 | input: 'test/samples/basic.js', 52 | plugins: [ 53 | modulepreload({ 54 | index: __dirname + '/index.html', 55 | shouldPreload: ({ code }) => 56 | !!code && code.includes('hi') 57 | })] 58 | }); 59 | 60 | await bundle.generate({ dir: 'output', format: 'es', }); 61 | 62 | const ACTUAL = 63 | await readFile(`${__dirname}/index.html`, 'utf-8'); 64 | 65 | assert.equal(ACTUAL, PRELOADS_A); 66 | assert.end(); 67 | }); 68 | 69 | test('takes async shouldPreload predicate', async function(assert) { 70 | await writeFile(__dirname + '/index.html', INDEX_SRC, 'utf-8') 71 | 72 | const bundle = await rollup({ 73 | input: 'test/samples/basic.js', 74 | plugins: [ 75 | modulepreload({ 76 | index: __dirname + '/index.html', 77 | async shouldPreload({ facadeModuleId }) { 78 | if (!facadeModuleId) return false; 79 | const file = await readFile(facadeModuleId, 'utf-8'); 80 | return file.includes('hi'); 81 | } 82 | })] 83 | }); 84 | 85 | await bundle.generate({ dir: 'output', format: 'es', }); 86 | 87 | const ACTUAL = 88 | await readFile(`${__dirname}/index.html`, 'utf-8'); 89 | 90 | assert.equal(ACTUAL, PRELOADS_A); 91 | assert.end(); 92 | }); 93 | --------------------------------------------------------------------------------