bennypowers / rollup-plugin-modulepreload Goto Github PK
View Code? Open in Web Editor NEWRollup plugin to add modulepreload links from generated chunks.
License: MIT License
Rollup plugin to add modulepreload links from generated chunks.
License: MIT License
For my modulepreload
use case, I don't have a static HTML file that I want to modify, I have a template file that I want to pass data to (e.g. the list of files that need preloading). It looks something like this:
{% for module in modulepreload %}
<link rel="modulepreload" href="/public/{{ module }}"></script>
{%- endfor %}
At the most basic level, what I need from a modulepreload
plugin for Rollup is something that inspects my bundle and gives me back a list files that need preloading. Then I (myself) can chose what I want to do with that list of files, and how I want to get it into my HTML.
There are also cases where the list of files to preload depends on what URL the user navigates to, and that can only be determined at run time, not at build time. In such cases a template would need more than just a single list, it would need a mapping of entry points to their static graphs (I've filed #3 to address that issue).
This issue is more about answering the question of how a developer gets the list of files to preload from this plugin to the HTML. I think letting them pass a function to the plugin that gets invoked with the entry graphs should be sufficient.
Only the build output should contain the generated preloads.
Is there a setting for that? Why does the plugin touch the index.html in the first place?
The default shouldPreload
function in this plugin will preload everything that is a dynamic import or has exports (without being a facade chunk). I'm not sure why that criteria was chosen.
Normally you want to preload everything in your initial static module graph, i.e. all the things that the browser would naturally load if given your primary module entry point. The idea is you want to tell the browser ahead of time what's going to be in the graph (so it can make the requests in parallel, without having to discover them).
In some cases you may also want to preload certain modules in the graph of a dynamic entry point (e.g. a router that dynamically loads all routes), but most of the time the reason they're in a dynamic entry point is they're conditionally loaded, so preloading them would defeat the purpose of conditionally loading them.
I think the default logic to determine the list of modules to preload should be:
Every chunk that's in the module graph of all static entry points.
Then, optionally, a developer may choose to specify dynamic entry chunks whose graph they also want to preload.
Lastly, I could see a use case for never preloading certain modules, so it probably makes sense to have a filter.
How does that sound? If you're interested in these changes I'd be happy to submit a PR. To give you an idea of what I'm thinking, here's how I'm currently getting the preload graphs for my entry modules (note: you do have to builds these graphs yourself, as this information isn't exposed by anything in ChunkInfo
):
{
generateBundle(options, bundle) {
// A mapping of entry chunk names to all dependencies in their
// static graphs
const entryChunksMap = {};
// Loop through all the chunks to detect entries.
for (const [fileName, chunkInfo] of Object.entries(bundle)) {
// This logic gets the graphs for both static and dynamic entries
// but you could imagine making it possible for a user to custom
// the conditional in this if-statement.
if (chunkInfo.isEntry || chunkInfo.isDynamicEntry) {
// A set of chunks in this entries graph.
const entryGraph = new Set([fileName]);
// A set of checked chunks to avoid circular dependencies.
const seen = new Set();
const imports = chunkInfo.imports.slice();
let importFileName;
while (importFileName = imports.shift()) {
const importChunkInfo = bundle[importFileName];
entryGraph.add(importChunkInfo.fileName);
// Add all inner chunk imports to the queue, checking for
// circular dependencies since chunks can import each other.
for (const i of importChunkInfo.imports) {
if (!seen.has(i)) {
seen.add(i);
imports.push(i);
}
}
}
entryChunksMap[chunkInfo.name] = [...entryGraph];
}
}
// Expose this somehow so the developer can create `modulepreload``
// tags base on these graphs.
console.log(entryChunksMap);
}
}
I imagine I'm just not setting it up right, but starting simply first, I'm getting some undefined messages when I try to build with any of the standard setups in the readme.
(in plugins)
modulepreload({
index: 'index.html',
shouldPreload: ({ facadeModuleId }) =>
fs.promises.readFile(facadeModuleId, 'utf-8')
.then(file => file.includes('INCLUDE THIS CHUNK')),
})
result:
[!] (plugin modulepreload) ReferenceError: fs is not defined
ReferenceError: fs is not defined
at shouldPreload (.../rollup.config.js:85:12)
(in plugins)
modulepreload({
index: 'index.html',
})
result:
[!] (plugin modulepreload) TypeError: Cannot read property 'length' of undefined
TypeError: Cannot read property 'length' of undefined
at defaultShouldPreload (.../node_modules/rollup-plugin-modulepreload/index.js:23:33)
After adding:
import fs from 'fs';
at the top of rollup config
Getting this:
[!] (plugin modulepreload) TypeError: The "path" argument must be of type string or an instance of Buffer or URL. Received null
TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string or an instance of Buffer or URL. Received null
at open (internal/fs/promises.js:306:10)
Here's my project for reference. I've created the modulepreload branch for tackling this problem and pushed code producing the build error.
https://github.com/SamuelFrost/portfolio/tree/modulepreload/portfolio-application
Hi Benny - I've been using a couple of your rollup plugins to create a built process for the HyperPress project. HyperPress is based on @Polymer - lit-element pwa-starter-kit. Rollup does a great of code-splitting and as you know, the downside of that is the initial visit lag while the chunks get pulled in and cached. So, followup visits exhibit great performance, whereas first visits suffer a full second increase in full load times. I thought this plugin would be a great solution for modulepreload of those chunks. But I've run into the following when running it:
TypeError: Cannot destructure property `writeFile` of 'undefined' or 'null'.
at Object.<anonymous> (/home/john/hyperpress/pressmedics/node_modules/rollup-plugin-modulepreload/index.js:2:36)
at Module._compile (internal/modules/cjs/loader.js:678:30)
at Module._extensions..js (internal/modules/cjs/loader.js:689:10)
at Object.require.extensions..js (/home/john/hyperpress/pressmedics/node_modules/rollup/bin/rollup:1132:17)
at Module.load (internal/modules/cjs/loader.js:589:32)
at tryModuleLoad (internal/modules/cjs/loader.js:528:12)
at Function.Module._load (internal/modules/cjs/loader.js:520:3)
at Module.require (internal/modules/cjs/loader.js:626:17)
at require (internal/modules/cjs/helpers.js:20:18)
at Object.<anonymous> (/home/john/hyperpress/pressmedics/rollup.config.js:10:33)
The rollup.config.js:
import babel from 'rollup-plugin-babel';
import { terser } from 'rollup-plugin-terser';
import minifyHTML from 'rollup-plugin-minify-html-literals';
import { modulepreload } from 'rollup-plugin-modulepreload';
import resolve from 'rollup-plugin-node-resolve';
//const production = !process.env.ROLLUP_WATCH;
export default [{
input: './src/components/ts-app.js',
output: [
{
dir: 'public/dist',
format: 'esm',
sourcemap: true
}
],
plugins: [
minifyHTML({
failOnError: true,
}),
resolve({
// use "jsnext:main" if possible
// legacy field pointing to ES6 module in third-party libraries,
// deprecated in favor of "pkg.module":
// - see: https://github.com/rollup/rollup/wiki/pkg.module
jsnext: true, // Default: false
}),
modulepreload({
prefix: 'modules',
index: 'public/index.html',
}),
terser()
]
},
{
input: './src/components/ts-app.js',
output: [
{
dir: 'public/dist_nomodule',
format: 'system'
}
],
plugins: [
minifyHTML({
failOnError: true,
}),
resolve({
// use "jsnext:main" if possible
// legacy field pointing to ES6 module in third-party libraries,
// deprecated in favor of "pkg.module":
// - see: https://github.com/rollup/rollup/wiki/pkg.module
jsnext: true, // Default: false
}),
modulepreload({
prefix: 'modules',
index: 'public/index.html',
}),
babel({
"presets": [
["@babel/preset-env", {"targets": {"ie": "11"}}]
],
"plugins": ["@babel/plugin-syntax-dynamic-import"]
}),
terser()
]
}];
I'm not sure what's causing it, but I may be missing the tree for the forest here too. I'm using gulp for some tasks such as moving root dist files, and testing against PRPL build. But nothing special there I think. Thanks for the assist.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.