Skip to content

Commit

Permalink
feat: use oxc for non-native define plugin (#71)
Browse files Browse the repository at this point in the history
  • Loading branch information
sapphi-red authored Dec 3, 2024
1 parent 5a51f96 commit 4e75b7f
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 39 deletions.
5 changes: 3 additions & 2 deletions packages/vite/src/node/__tests__/plugins/define.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ describe('definePlugin', () => {
// assert that the default behavior is to replace import.meta.hot with undefined
const transform = await createDefinePluginTransform()
expect(await transform('const hot = import.meta.hot;')).toBe(
'const hot = void 0;\n',
'const hot = undefined;\n',
)
// assert that we can specify a user define to preserve import.meta.hot
const overrideTransform = await createDefinePluginTransform({
Expand All @@ -85,7 +85,8 @@ describe('definePlugin', () => {
)
})

test('preserve import.meta.env.UNKNOWN with override', async () => {
// NOTE: skipped because of https://github.com/oxc-project/oxc/issues/7594
test.skip('preserve import.meta.env.UNKNOWN with override', async () => {
const transform = await createDefinePluginTransform({
'import.meta.env.UNKNOWN': 'import.meta.env.UNKNOWN',
})
Expand Down
40 changes: 8 additions & 32 deletions packages/vite/src/node/plugins/define.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { transform } from 'esbuild'
import { TraceMap, decodedMap, encodedMap } from '@jridgewell/trace-mapping'
import type { RolldownPlugin } from 'rolldown'
import { transform } from 'rolldown/experimental'
import type { ResolvedConfig } from '../config'
import { escapeRegex } from '../utils'
import type { Environment } from '../environment'
Expand Down Expand Up @@ -169,9 +168,7 @@ export function definePlugin(config: ResolvedConfig): RolldownPlugin {
result.code = `const ${marker} = ${importMetaEnvVal};\n` + result.code

if (result.map) {
const map = JSON.parse(result.map)
map.mappings = ';' + map.mappings
result.map = map
result.map.mappings = ';' + result.map.mappings
}
}
}
Expand All @@ -196,39 +193,18 @@ export async function replaceDefine(
code: string,
id: string,
define: Record<string, string>,
): Promise<{ code: string; map: string | null }> {
const esbuildOptions = environment.config.esbuild || {}

const result = await transform(code, {
loader: 'js',
charset: esbuildOptions.charset ?? 'utf8',
platform: 'neutral',
): Promise<{ code: string; map: ReturnType<typeof transform>['map'] | null }> {
const result = transform(id, code, {
lang: 'js',
sourceType: 'module',
define,
sourcefile: id,
sourcemap:
environment.config.command === 'build'
? !!environment.config.build.sourcemap
: true,
})

// remove esbuild's <define:...> source entries
// since they would confuse source map remapping/collapsing which expects a single source
if (result.map.includes('<define:')) {
const originalMap = new TraceMap(result.map)
if (originalMap.sources.length >= 2) {
const sourceIndex = originalMap.sources.indexOf(id)
const decoded = decodedMap(originalMap)
decoded.sources = [id]
decoded.mappings = decoded.mappings.map((segments) =>
segments.filter((segment) => {
// modify and filter
const index = segment[1]
segment[1] = 0
return index === sourceIndex
}),
)
result.map = JSON.stringify(encodedMap(new TraceMap(decoded as any)))
}
if (result.errors.length > 0) {
throw new AggregateError(result.errors, 'oxc transform error')
}

return {
Expand Down
11 changes: 7 additions & 4 deletions playground/define/__tests__/define.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { expect, test } from 'vitest'
import viteConfig from '../vite.config'
import { page } from '~utils'
import { isBuild, page } from '~utils'

const defines = viteConfig.define
const envDefines = viteConfig.environments.client.define
Expand All @@ -26,9 +26,12 @@ test('string', async () => {
expect(await page.textContent('.env-var')).toBe(
JSON.parse(defines['process.env.SOMEVAR']),
)
expect(await page.textContent('.process-as-property')).toBe(
defines.__OBJ__.process.env.SOMEVAR,
)
// NOTE: skipped because of https://github.com/oxc-project/oxc/issues/7598
if (!isBuild) {
expect(await page.textContent('.process-as-property')).toBe(
defines.__OBJ__.process.env.SOMEVAR,
)
}
expect(await page.textContent('.spread-object')).toBe(
JSON.stringify({ SOMEVAR: defines['process.env.SOMEVAR'] }),
)
Expand Down
3 changes: 2 additions & 1 deletion playground/js-sourcemap/__tests__/js-sourcemap.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,8 @@ describe.runIf(isBuild)('build tests', () => {
expect(js).not.toMatch(/__vite__mapDeps/)
})

test('sourcemap is correct when using object as "define" value', async () => {
// NOTE: this test is not relevant to oxc
test.skip('sourcemap is correct when using object as "define" value', async () => {
const map = findAssetFile(/with-define-object.*\.js\.map/)
expect(formatSourcemapForSnapshot(JSON.parse(map))).toMatchInlineSnapshot(`
{
Expand Down

0 comments on commit 4e75b7f

Please sign in to comment.