Skip to content

Commit

Permalink
fix: avoid using import.meta.url for relative assets if output is n…
Browse files Browse the repository at this point in the history
…ot ESM (fixes #9297) (#9381)
  • Loading branch information
sapphi-red authored Aug 9, 2022
1 parent 10757b8 commit 6d95225
Show file tree
Hide file tree
Showing 16 changed files with 105 additions and 30 deletions.
66 changes: 57 additions & 9 deletions packages/vite/src/node/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import path from 'node:path'
import colors from 'picocolors'
import type {
ExternalOption,
InternalModuleFormat,
ModuleFormat,
OutputOptions,
Plugin,
Expand Down Expand Up @@ -826,6 +827,50 @@ function injectSsrFlag<T extends Record<string, any>>(
return { ...(options ?? {}), ssr: true } as T & { ssr: boolean }
}

/*
The following functions are copied from rollup
https://github.com/rollup/rollup/blob/c5269747cd3dd14c4b306e8cea36f248d9c1aa01/src/ast/nodes/MetaProperty.ts#L189-L232
https://github.com/rollup/rollup
The MIT License (MIT)
Copyright (c) 2017 [these people](https://github.com/rollup/rollup/graphs/contributors)
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 SOFTWARE.
*/
const getResolveUrl = (path: string, URL = 'URL') => `new ${URL}(${path}).href`

const getRelativeUrlFromDocument = (relativePath: string, umd = false) =>
getResolveUrl(
`'${relativePath}', ${
umd ? `typeof document === 'undefined' ? location.href : ` : ''
}document.currentScript && document.currentScript.src || document.baseURI`
)

const relativeUrlMechanisms: Record<
InternalModuleFormat,
(relativePath: string) => string
> = {
amd: (relativePath) => {
if (relativePath[0] !== '.') relativePath = './' + relativePath
return getResolveUrl(`require.toUrl('${relativePath}'), document.baseURI`)
},
cjs: (relativePath) =>
`(typeof document === 'undefined' ? ${getResolveUrl(
`'file:' + __dirname + '/${relativePath}'`,
`(require('u' + 'rl').URL)`
)} : ${getRelativeUrlFromDocument(relativePath)})`,
es: (relativePath) => getResolveUrl(`'${relativePath}', import.meta.url`),
iife: (relativePath) => getRelativeUrlFromDocument(relativePath),
system: (relativePath) => getResolveUrl(`'${relativePath}', module.meta.url`),
umd: (relativePath) =>
`(typeof document === 'undefined' && typeof location === 'undefined' ? ${getResolveUrl(
`'file:' + __dirname + '/${relativePath}'`,
`(require('u' + 'rl').URL)`
)} : ${getRelativeUrlFromDocument(relativePath, true)})`
}
/* end of copy */

export type RenderBuiltAssetUrl = (
filename: string,
type: {
Expand All @@ -842,10 +887,13 @@ export function toOutputFilePathInString(
hostId: string,
hostType: 'js' | 'css' | 'html',
config: ResolvedConfig,
format: InternalModuleFormat,
toRelative: (
filename: string,
hostType: string
) => string | { runtime: string } = toImportMetaURLBasedRelativePath
) => string | { runtime: string } = getToImportMetaURLBasedRelativePath(
format
)
): string | { runtime: string } {
const { renderBuiltUrl } = config.experimental
let relative = config.base === '' || config.base === './'
Expand Down Expand Up @@ -873,15 +921,15 @@ export function toOutputFilePathInString(
return config.base + filename
}

function toImportMetaURLBasedRelativePath(
filename: string,
importer: string
): { runtime: string } {
return {
runtime: `new URL(${JSON.stringify(
function getToImportMetaURLBasedRelativePath(
format: InternalModuleFormat
): (filename: string, importer: string) => { runtime: string } {
const toRelativePath = relativeUrlMechanisms[format]
return (filename, importer) => ({
runtime: toRelativePath(
path.posix.relative(path.dirname(importer), filename)
)},import.meta.url).href`
}
)
})
}

export function toOutputFilePathWithoutRuntime(
Expand Down
8 changes: 5 additions & 3 deletions packages/vite/src/node/plugins/asset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ export function assetPlugin(config: ResolvedConfig): Plugin {
return `export default ${JSON.stringify(url)}`
},

renderChunk(code, chunk) {
renderChunk(code, chunk, outputOptions) {
let match: RegExpExecArray | null
let s: MagicString | undefined

Expand All @@ -115,7 +115,8 @@ export function assetPlugin(config: ResolvedConfig): Plugin {
'asset',
chunk.fileName,
'js',
config
config,
outputOptions.format
)
const replacementString =
typeof replacement === 'string'
Expand All @@ -138,7 +139,8 @@ export function assetPlugin(config: ResolvedConfig): Plugin {
'public',
chunk.fileName,
'js',
config
config,
outputOptions.format
)
const replacementString =
typeof replacement === 'string'
Expand Down
11 changes: 3 additions & 8 deletions packages/vite/src/node/plugins/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -308,7 +308,7 @@ export function webWorkerPlugin(config: ResolvedConfig): Plugin {
}
},

renderChunk(code, chunk) {
renderChunk(code, chunk, outputOptions) {
let s: MagicString
const result = () => {
return (
Expand All @@ -334,7 +334,8 @@ export function webWorkerPlugin(config: ResolvedConfig): Plugin {
'asset',
chunk.fileName,
'js',
config
config,
outputOptions.format
)
const replacementString =
typeof replacement === 'string'
Expand All @@ -349,12 +350,6 @@ export function webWorkerPlugin(config: ResolvedConfig): Plugin {
}
)
}

// TODO: check if this should be removed
if (config.isWorker) {
s = s.replace('import.meta.url', 'self.location.href')
return result()
}
}
if (!isWorker) {
const workerMap = workerCache.get(config)!
Expand Down
6 changes: 6 additions & 0 deletions playground/legacy/__tests__/legacy.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,12 @@ test('should load dynamic import with css', async () => {
await untilUpdated(() => getColor('#dynamic-css'), 'red', true)
})

test('asset url', async () => {
expect(await page.textContent('#asset-path')).toMatch(
isBuild ? /\/assets\/vite\.\w+\.svg/ : '/vite.svg'
)
})

describe.runIf(isBuild)('build', () => {
test('should generate correct manifest', async () => {
const manifest = readManifest()
Expand Down
1 change: 1 addition & 0 deletions playground/legacy/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,5 @@ <h1 id="app"></h1>
<div id="assets"></div>
<button id="dynamic-css-button">dynamic css</button>
<div id="dynamic-css"></div>
<div id="asset-path"></div>
<script type="module" src="./main.js"></script>
4 changes: 3 additions & 1 deletion playground/legacy/main.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import './style.css'
import './vite.svg'
import viteSvgPath from './vite.svg'

async function run() {
const { fn } = await import('./async.js')
Expand Down Expand Up @@ -51,6 +51,8 @@ document
text('#dynamic-css', 'dynamic import css')
})

text('#asset-path', viteSvgPath)

function text(el, text) {
document.querySelector(el).textContent = text
}
7 changes: 6 additions & 1 deletion playground/worker/__tests__/es/es-worker.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@ test('normal', async () => {
'worker bundle with plugin success!',
true
)
await untilUpdated(
() => page.textContent('.asset-url'),
isBuild ? '/es/assets/vite.svg' : '/es/vite.svg',
true
)
})

test('TS output', async () => {
Expand Down Expand Up @@ -51,7 +56,7 @@ describe.runIf(isBuild)('build', () => {
test('inlined code generation', async () => {
const assetsDir = path.resolve(testDir, 'dist/es/assets')
const files = fs.readdirSync(assetsDir)
expect(files.length).toBe(27)
expect(files.length).toBe(28)
const index = files.find((f) => f.includes('main-module'))
const content = fs.readFileSync(path.resolve(assetsDir, index), 'utf-8')
const worker = files.find((f) => f.includes('my-worker'))
Expand Down
7 changes: 6 additions & 1 deletion playground/worker/__tests__/iife/iife-worker.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@ test('normal', async () => {
() => page.textContent('.bundle-with-plugin'),
'worker bundle with plugin success!'
)
await untilUpdated(
() => page.textContent('.asset-url'),
isBuild ? '/iife/assets/vite.svg' : '/iife/vite.svg',
true
)
})

test('TS output', async () => {
Expand Down Expand Up @@ -41,7 +46,7 @@ describe.runIf(isBuild)('build', () => {
test('inlined code generation', async () => {
const assetsDir = path.resolve(testDir, 'dist/iife/assets')
const files = fs.readdirSync(assetsDir)
expect(files.length).toBe(15)
expect(files.length).toBe(16)
const index = files.find((f) => f.includes('main-module'))
const content = fs.readFileSync(path.resolve(assetsDir, index), 'utf-8')
const worker = files.find((f) => f.includes('my-worker'))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,19 @@ test('normal', async () => {
'worker bundle with plugin success!',
true
)
await untilUpdated(
() => page.textContent('.asset-url'),
isBuild ? '/other-assets/vite' : '/vite.svg',
true
)
})

test('TS output', async () => {
await untilUpdated(() => page.textContent('.pong-ts-output'), 'pong', true)
})

test('inlined', async () => {
// TODO: inline worker should inline assets
test.skip('inlined', async () => {
await untilUpdated(() => page.textContent('.pong-inline'), 'pong', true)
})

Expand Down Expand Up @@ -65,7 +71,7 @@ describe.runIf(isBuild)('build', () => {
)

// worker should have all imports resolved and no exports
expect(workerContent).not.toMatch(`import`)
expect(workerContent).not.toMatch(/import(?!\.)/) // accept import.meta.url
expect(workerContent).not.toMatch(`export`)
// chunk
expect(content).toMatch(`new Worker(""+new URL("../worker-entries/`)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ describe.runIf(isBuild)('build', () => {

const files = fs.readdirSync(assetsDir)
// should have 2 worker chunk
expect(files.length).toBe(30)
expect(files.length).toBe(31)
const index = files.find((f) => f.includes('main-module'))
const content = fs.readFileSync(path.resolve(assetsDir, index), 'utf-8')
const indexSourcemap = getSourceMapUrl(content)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ describe.runIf(isBuild)('build', () => {

const files = fs.readdirSync(assetsDir)
// should have 2 worker chunk
expect(files.length).toBe(15)
expect(files.length).toBe(16)
const index = files.find((f) => f.includes('main-module'))
const content = fs.readFileSync(path.resolve(assetsDir, index), 'utf-8')
const indexSourcemap = getSourceMapUrl(content)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ describe.runIf(isBuild)('build', () => {
const assetsDir = path.resolve(testDir, 'dist/iife-sourcemap/assets')
const files = fs.readdirSync(assetsDir)
// should have 2 worker chunk
expect(files.length).toBe(30)
expect(files.length).toBe(31)
const index = files.find((f) => f.includes('main-module'))
const content = fs.readFileSync(path.resolve(assetsDir, index), 'utf-8')
const indexSourcemap = getSourceMapUrl(content)
Expand Down
2 changes: 2 additions & 0 deletions playground/worker/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,13 @@ <h2 class="format-iife">format iife:</h2>
<span class="classname">.pong</span>
<span class="classname">.mode</span>
<span class="classname">.bundle-with-plugin</span>
<span class="classname">.asset-url</span>
</p>
<div>
<div>Response from worker: <span class="pong"></span></div>
<div>mode: <span class="mode"></span></div>
<div>bundle-with-plugin: <span class="bundle-with-plugin"></span></div>
<div>asset-url: <span class="asset-url"></span></div>
</div>

<p>
Expand Down
5 changes: 3 additions & 2 deletions playground/worker/my-worker.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import { msg as msgFromDep } from 'dep-to-optimize'
import { mode, msg } from './modules/workerImport'
import { bundleWithPlugin } from './modules/test-plugin'
import viteSvg from './vite.svg'

self.onmessage = (e) => {
if (e.data === 'ping') {
self.postMessage({ msg, mode, bundleWithPlugin })
self.postMessage({ msg, mode, bundleWithPlugin, viteSvg })
}
}
self.postMessage({ msg, mode, bundleWithPlugin, msgFromDep })
self.postMessage({ msg, mode, bundleWithPlugin, msgFromDep, viteSvg })

// for sourcemap
console.log('my-worker.js')
1 change: 1 addition & 0 deletions playground/worker/vite.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions playground/worker/worker/main-module.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ worker.addEventListener('message', (e) => {
text('.pong', e.data.msg)
text('.mode', e.data.mode)
text('.bundle-with-plugin', e.data.bundleWithPlugin)
text('.asset-url', e.data.viteSvg)
})

const inlineWorker = new InlineWorker()
Expand Down

0 comments on commit 6d95225

Please sign in to comment.