Skip to content

Commit

Permalink
feat: modulepreload polyfill (#4058)
Browse files Browse the repository at this point in the history
  • Loading branch information
patak-dev authored Jul 29, 2021
1 parent 31444ec commit cb75dbd
Show file tree
Hide file tree
Showing 7 changed files with 155 additions and 12 deletions.
15 changes: 15 additions & 0 deletions docs/config/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -543,6 +543,21 @@ createServer()
Note the build will fail if the code contains features that cannot be safely transpiled by esbuild. See [esbuild docs](https://esbuild.github.io/content-types/#javascript) for more details.
### build.polyfillModulePreload
- **Type:** `boolean`
- **Default:** `true`
Whether to automatically inject [module preload polyfill](https://guybedford.com/es-module-preloading-integrity#modulepreload-polyfill).
If set to `true`, the polyfill is auto injected into the proxy module of each `index.html` entry. If the build is configured to use a non-html custom entry via `build.rollupOptions.input`, then it is necessary to manually import the polyfill in your custom entry:
```js
import 'vite/modulepreload-polyfill'
```
Note: the polyfill does **not** apply to [Library Mode](/guide/build#library-mode). If you need to support browsers without native dynamic import, you should probably avoid using it in your library.
### build.outDir
- **Type:** `string`
Expand Down
7 changes: 7 additions & 0 deletions docs/guide/backend-integration.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,13 @@ Or you can follow these steps to configure it manually:
})
```

If you haven't disabled the [module preload polyfill](/config/#polyfillmodulepreload), you also need to import the polyfill in your entry

```js
// add the beginning of your app entry
import 'vite/modulepreload-polyfill'
```

2. For development, inject the following in your server's HTML template (substitute `http://localhost:3000` with the local URL Vite is running at):

```html
Expand Down
7 changes: 7 additions & 0 deletions packages/vite/src/node/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,12 @@ export interface BuildOptions {
* https://esbuild.github.io/content-types/#javascript for more details.
*/
target?: 'modules' | TransformOptions['target'] | false
/**
* whether to inject module preload polyfill.
* Note: does not apply to library mode.
* @default true
*/
polyfillModulePreload?: boolean
/**
* whether to inject dynamic import polyfill.
* Note: does not apply to library mode.
Expand Down Expand Up @@ -211,6 +217,7 @@ export type ResolvedBuildOptions = Required<
export function resolveBuildOptions(raw?: BuildOptions): ResolvedBuildOptions {
const resolved: ResolvedBuildOptions = {
target: 'modules',
polyfillModulePreload: true,
outDir: 'dist',
assetsDir: 'assets',
assetsInlineLimit: 4096,
Expand Down
6 changes: 6 additions & 0 deletions packages/vite/src/node/plugins/html.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {
getAssetFilename
} from './asset'
import { isCSSRequest, chunkToEmittedCssFileMap } from './css'
import { modulePreloadPolyfillId } from './modulePreloadPolyfill'
import {
AttributeNode,
NodeTransform,
Expand Down Expand Up @@ -263,6 +264,11 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin {

processedHtml.set(id, s.toString())

// inject module preload polyfill
if (config.build.polyfillModulePreload) {
js = `import "${modulePreloadPolyfillId}";\n${js}`
}

return js
}
},
Expand Down
28 changes: 16 additions & 12 deletions packages/vite/src/node/plugins/importAnalysisBuild.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,30 +18,29 @@ export const preloadMarker = `__VITE_PRELOAD__`
export const preloadBaseMarker = `__VITE_PRELOAD_BASE__`

const preloadHelperId = 'vite/preload-helper'
const preloadCode = `let scriptRel;const seen = {};const base = '${preloadBaseMarker}';export const ${preloadMethod} = ${preload.toString()}`
const preloadMarkerRE = new RegExp(`"${preloadMarker}"`, 'g')

/**
* Helper for preloading CSS and direct imports of async chunks in parallel to
* the async chunk itself.
*/

function detectScriptRel() {
// @ts-ignore
const relList = document.createElement('link').relList
// @ts-ignore
return relList && relList.supports && relList.supports('modulepreload')
? 'modulepreload'
: 'preload'
}

declare const scriptRel: string
function preload(baseModule: () => Promise<{}>, deps?: string[]) {
// @ts-ignore
if (!__VITE_IS_MODERN__ || !deps || deps.length === 0) {
return baseModule()
}

// @ts-ignore
if (scriptRel === undefined) {
// @ts-ignore
const relList = document.createElement('link').relList
// @ts-ignore
scriptRel =
relList && relList.supports && relList.supports('modulepreload')
? 'modulepreload'
: 'preload'
}

return Promise.all(
deps.map((dep) => {
// @ts-ignore
Expand Down Expand Up @@ -84,6 +83,11 @@ export function buildImportAnalysisPlugin(config: ResolvedConfig): Plugin {
const ssr = !!config.build.ssr
const insertPreload = !(ssr || !!config.build.lib)

const scriptRel = config.build.polyfillModulePreload
? `'modulepreload'`
: `(${detectScriptRel.toString()})()`
const preloadCode = `const scriptRel = ${scriptRel};const seen = {};const base = '${preloadBaseMarker}';export const ${preloadMethod} = ${preload.toString()}`

return {
name: 'vite:import-analysis',

Expand Down
4 changes: 4 additions & 0 deletions packages/vite/src/node/plugins/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { assetPlugin } from './asset'
import { clientInjectionsPlugin } from './clientInjections'
import { htmlInlineScriptProxyPlugin } from './html'
import { wasmPlugin } from './wasm'
import { modulePreloadPolyfillPlugin } from './modulePreloadPolyfill'
import { webWorkerPlugin } from './worker'
import { preAliasPlugin } from './preAlias'
import { definePlugin } from './define'
Expand All @@ -30,6 +31,9 @@ export async function resolvePlugins(
isBuild ? null : preAliasPlugin(),
aliasPlugin({ entries: config.resolve.alias }),
...prePlugins,
config.build.polyfillModulePreload
? modulePreloadPolyfillPlugin(config)
: null,
resolvePlugin({
...config.resolve,
root: config.root,
Expand Down
100 changes: 100 additions & 0 deletions packages/vite/src/node/plugins/modulePreloadPolyfill.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import { ResolvedConfig } from '..'
import { Plugin } from '../plugin'
import { isModernFlag } from './importAnalysisBuild'

export const modulePreloadPolyfillId = 'vite/modulepreload-polyfill'

export function modulePreloadPolyfillPlugin(config: ResolvedConfig): Plugin {
const skip = config.build.ssr
let polyfillString: string | undefined

return {
name: 'vite:modulepreload-polyfill',
resolveId(id) {
if (id === modulePreloadPolyfillId) {
return id
}
},
load(id) {
if (id === modulePreloadPolyfillId) {
if (skip) {
return ''
}
if (!polyfillString) {
polyfillString =
`const p = ${polyfill.toString()};` + `${isModernFlag}&&p();`
}
return polyfillString
}
}
}
}

/**
The following polyfill function is meant to run in the browser and adapted from
https://github.com/guybedford/es-module-shims
MIT License
Copyright (C) 2018-2021 Guy Bedford
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
*/

declare const document: any
declare const MutationObserver: any
declare const fetch: any

function polyfill() {
const relList = document.createElement('link').relList
if (relList && relList.supports && relList.supports('modulepreload')) {
return
}

for (const link of document.querySelectorAll('link[rel="modulepreload"]')) {
processPreload(link)
}

new MutationObserver((mutations: any) => {
for (const mutation of mutations) {
if (mutation.type !== 'childList') {
continue
}
for (const node of mutation.addedNodes) {
if (node.tagName === 'LINK' && node.rel === 'modulepreload')
processPreload(node)
}
}
}).observe(document, { childList: true, subtree: true })

function getFetchOpts(script: any) {
const fetchOpts = {} as any
if (script.integrity) fetchOpts.integrity = script.integrity
if (script.referrerpolicy) fetchOpts.referrerPolicy = script.referrerpolicy
if (script.crossorigin === 'use-credentials')
fetchOpts.credentials = 'include'
else if (script.crossorigin === 'anonymous') fetchOpts.credentials = 'omit'
else fetchOpts.credentials = 'same-origin'
return fetchOpts
}

function processPreload(link: any) {
if (link.ep)
// ep marker = processed
return
link.ep = true
// prepopulate the load record
const fetchOpts = getFetchOpts(link)
fetch(link.href, fetchOpts)
}
}

0 comments on commit cb75dbd

Please sign in to comment.