Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(html): move importmap before module scripts #9392

Merged
merged 14 commits into from Aug 21, 2022
60 changes: 60 additions & 0 deletions packages/vite/src/node/plugins/html.ts
Expand Up @@ -7,6 +7,7 @@ import type {
SourceMapInput
} from 'rollup'
import MagicString from 'magic-string'
import colors from 'picocolors'
import type {
AttributeNode,
CompilerError,
Expand Down Expand Up @@ -52,6 +53,10 @@ const inlineImportRE =
/(?<!(?<!\.\.)\.)\bimport\s*\(("([^"]|(?<=\\)")*"|'([^']|(?<=\\)')*')\)/g
const htmlLangRE = /\.(html|htm)$/

const importMapRE =
/[ \t]*<script[^>]*type\s*=\s*["']?importmap["']?[^>]*>.*?<\/script>/is
const moduleScriptRE = /[ \t]*<script[^>]*type\s*=\s*["']?module["']?[^>]*>/is

export const isHTMLProxy = (id: string): boolean => htmlProxyRE.test(id)

export const isHTMLRequest = (request: string): boolean =>
Expand Down Expand Up @@ -218,6 +223,61 @@ function handleParseError(
)
}

/**
* Check if importmap is after any script module. Warn user if so.
* Must be added before pre plugins.
*/
export function preHtmlImportMapPlugin(config: ResolvedConfig): Plugin {
return {
name: 'vite:pre-html-importmap',
transformIndexHtml: {
bluwy marked this conversation as resolved.
Show resolved Hide resolved
enforce: 'pre',
transform(html, ctx) {
const importMapIndex = html.match(importMapRE)?.index
if (!importMapIndex) return

const moduleScriptIndex = html.match(moduleScriptRE)?.index
if (!moduleScriptIndex) return

sapphi-red marked this conversation as resolved.
Show resolved Hide resolved
if (moduleScriptIndex < importMapIndex) {
const relativeHtml = path.relative(config.root, ctx.filename)
config.logger.warnOnce(
colors.yellow(
colors.bold(
`(!) <script type="importmap"> should come before <script type="module"> in /${relativeHtml}`
)
)
)
}
}
}
}
}

/**
* Move importmap to top of <head> with `transformIndexHtml`.
* Must be added after post plugins.
*/
export function postHtmlImportMapPlugin(): Plugin {
return {
name: 'vite:post-html-importmap',
transformIndexHtml(html) {
if (!moduleScriptRE.test(html)) return

let importMap: string | undefined
html = html.replace(importMapRE, (match) => {
importMap = match
return ''
})
if (importMap) {
html = html.replace(moduleScriptRE, (match) => `${importMap}\n${match}`)
}
sapphi-red marked this conversation as resolved.
Show resolved Hide resolved

return html
}
}
}

/**
* Compiles index.html into an entry js module
*/
Expand Down
9 changes: 8 additions & 1 deletion packages/vite/src/node/plugins/index.ts
Expand Up @@ -12,7 +12,12 @@ import { importAnalysisPlugin } from './importAnalysis'
import { cssPlugin, cssPostPlugin } from './css'
import { assetPlugin } from './asset'
import { clientInjectionsPlugin } from './clientInjections'
import { buildHtmlPlugin, htmlInlineProxyPlugin } from './html'
import {
buildHtmlPlugin,
htmlInlineProxyPlugin,
postHtmlImportMapPlugin,
preHtmlImportMapPlugin
} from './html'
import { wasmFallbackPlugin, wasmHelperPlugin } from './wasm'
import { modulePreloadPolyfillPlugin } from './modulePreloadPolyfill'
import { webWorkerPlugin } from './worker'
Expand Down Expand Up @@ -42,6 +47,7 @@ export async function resolvePlugins(
isBuild ? metadataPlugin() : null,
preAliasPlugin(config),
aliasPlugin({ entries: config.resolve.alias }),
preHtmlImportMapPlugin(config),
...prePlugins,
config.build.polyfillModulePreload
? modulePreloadPolyfillPlugin(config)
Expand Down Expand Up @@ -93,6 +99,7 @@ export async function resolvePlugins(
importGlobPlugin(config),
...postPlugins,
...buildPlugins.post,
postHtmlImportMapPlugin(),
// internal server-only plugins are always applied after everything else
...(isBuild
? []
Expand Down
8 changes: 7 additions & 1 deletion playground/external/__tests__/external.spec.ts
@@ -1,4 +1,10 @@
import { isBuild, page } from '~utils'
import { browserLogs, isBuild, isServe, page } from '~utils'

test.runIf(isServe)('importmap', () => {
bluwy marked this conversation as resolved.
Show resolved Hide resolved
expect(browserLogs).not.toContain(
'An import map is added after module script load was triggered.'
)
})

describe.runIf(isBuild)('build', () => {
test('should externalize imported packages', async () => {
Expand Down
16 changes: 15 additions & 1 deletion playground/html/__tests__/html.spec.ts
@@ -1,5 +1,13 @@
import { beforeAll, describe, expect, test } from 'vitest'
import { editFile, getColor, isBuild, isServe, page, viteTestUrl } from '~utils'
import {
browserLogs,
editFile,
getColor,
isBuild,
isServe,
page,
viteTestUrl
} from '~utils'

function testPage(isNested: boolean) {
test('pre transform', async () => {
Expand Down Expand Up @@ -242,3 +250,9 @@ describe.runIf(isServe)('invalid', () => {
expect(content).toBeTruthy()
})
})

test.runIf(isServe)('importmap', () => {
bluwy marked this conversation as resolved.
Show resolved Hide resolved
expect(browserLogs).not.toContain(
'An import map is added after module script load was triggered.'
)
})
19 changes: 19 additions & 0 deletions playground/html/vite.config.js
Expand Up @@ -160,6 +160,25 @@ ${
}
]
}
},
{
name: 'head-prepend-importmap',
transformIndexHtml() {
return [
{
tag: 'script',
attrs: { type: 'importmap' },
children: `
{
"imports": {
"vue": "https://unpkg.com/vue@3.2.0/dist/vue.runtime.esm-browser.js"
}
}
`,
injectTo: 'head-prepend'
}
]
}
}
]
}