Skip to content

Commit

Permalink
fix: allow ssr css preloads in preload-helper (#1734)
Browse files Browse the repository at this point in the history
  • Loading branch information
bompus committed Jan 26, 2021
1 parent 71fcfdf commit 1dfda16
Showing 1 changed file with 19 additions and 11 deletions.
30 changes: 19 additions & 11 deletions packages/vite/src/node/plugins/importAnaysisBuild.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,38 +17,46 @@ export const preloadMethod = `__vitePreload`
export const preloadMarker = `__VITE_PRELOAD__`

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

/**
* Helper for preloading CSS and direct imports of async chunks in parallell to
* Helper for preloading CSS and direct imports of async chunks in parallel to
* the async chunk itself.
*/
function preload(baseModule: () => Promise<{}>, deps?: string[]) {
// @ts-ignore
if (!__VITE_IS_MODERN__ || !deps) {
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
if (dep in seen) return
// @ts-ignore
seen[dep] = true
const isCss = /\.css$/.test(dep)
const isCss = dep.endsWith('.css')
const cssSelector = isCss ? '[rel="stylesheet"]' : ''
// @ts-ignore check if the file is already preloaded by SSR markup
if (document.querySelector(`link[href="${dep}"]`)) {
if (document.querySelector(`link[href="${dep}"]${cssSelector}`)) {
return
}
// @ts-ignore
const link = document.createElement('link')
link.rel = isCss
? 'stylesheet'
: link.relList &&
link.relList.supports &&
link.relList.supports('modulepreload')
? 'modulepreload'
: 'preload'
// @ts-ignore
link.rel = isCss ? 'stylesheet' : scriptRel
if (!isCss) {
link.as = 'script'
link.crossOrigin = ''
Expand Down

0 comments on commit 1dfda16

Please sign in to comment.