Giter VIP home page Giter VIP logo

rollup-plugin-modulepreload's Introduction

rollup-plugin-modulepreload

Rollup plugin to add modulepreload links from generated chunks. Users may customize which chunks are preloaded using the shouldPreload option.

Usage

import config from './rollup.config.rest.js'
import modulepreload from 'rollup-plugin-modulepreload';

export default {
  plugins: [
    modulepreload({
      prefix: 'modules',
      index: 'public/index.html',
    })
  ]
}

This will write something like the following to the <head> of index.html

<link rel="modulepreload" href="modules/chunk-47ckl37a.js">

Options

Name Accepts Default
index Path to index.html to modify. undefined
prefix Path to prepend to chunk filenames in link tag href attribute. your bundle's dir option
shouldPreload Predicate which takes a ChunkInfo Default predicate

Determining Which Chunks to Preload

You can customize the function which determines whether or not to preload a chunk by passing a shouldPreload predicate, which takes a ChunkInfo object.

It can be synchronous:

function shouldPreload({ code }) {
  return !!code && code.includes('INCLUDE THIS CHUNK');
}

export default {
  input: 'src/index.js',
  plugins: [
    modulepreload({
      index: 'public/index.html',
      prefix: 'modules',
      shouldPreload,
    })
  ]
}

or asynchronous:

import { readFile } from 'fs/promises'; // node ^14

async function shouldPreload(chunk) {
  if (!chunk.facadeModuleId)
    return false;

  const file =
    await readFile(chunk.facadeModuleId, 'utf-8');

  return file.includes('INCLUDE THIS CHUNK');
}

export default {
  input: 'src/index.js',
  plugins: [
    modulepreload({
      index: 'public/index.html',
      prefix: 'modules',
      shouldPreload,
    })
  ]
}

The Default Predicate is :

const defaultShouldPreload =
  ({ exports, facadeModuleId, isDynamicEntry }) =>
    !!(
      // preload dynamically imported chunks
      isDynamicEntry ||
      // preload generated intermediate chunks
      (exports && exports.length && !facadeModuleId)
    );

rollup-plugin-modulepreload's People

Contributors

bennypowers avatar nstringham avatar

Stargazers

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

Watchers

 avatar  avatar  avatar

rollup-plugin-modulepreload's Issues

Default build settings not working for me. Giving various undefined issues.

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

Expose the modulepreload entry graphs rather than modifying HTML

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.

The default shouldPreload logic seems incorrect

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);
  }
}

Rollup: TypeError: Cannot destructure property `writeFile` of 'undefined' or 'null'.

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.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.