Skip to content

Commit

Permalink
feat(imports): support import attributes
Browse files Browse the repository at this point in the history
  • Loading branch information
redfox-mx committed Jun 15, 2024
1 parent b4b4acf commit 90f685b
Show file tree
Hide file tree
Showing 6 changed files with 53 additions and 10 deletions.
18 changes: 15 additions & 3 deletions packages/vite/src/node/plugins/importAnalysis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import {
} from '../server/hmr'
import {
createDebugger,
evalValue,
fsPathFromUrl,
generateCodeFrame,
injectQuery,
Expand Down Expand Up @@ -294,6 +295,7 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {
url: string,
pos: number,
forceSkipImportAnalysis: boolean = false,
attributes?: Record<string, string>,
): Promise<[string, string]> => {
url = stripBase(url, base)

Expand All @@ -317,7 +319,7 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {
}
}

const resolved = await this.resolve(url, importerFile)
const resolved = await this.resolve(url, importerFile, { attributes })

if (!resolved || resolved.meta?.['vite:alias']?.noResolved) {
// in ssr, we should let node handle the missing modules
Expand Down Expand Up @@ -491,8 +493,13 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {

const isDynamicImport = dynamicIndex > -1

// strip import attributes as we can process them ourselves
// Grab the import attributes
let importAttributes: Record<string, any> | undefined = undefined
if (!isDynamicImport && attributeIndex > -1) {
const raw = source.substring(attributeIndex, expEnd)
importAttributes = evalValue<{}>(raw)

// strip import attributes as we can process them ourselves
str().remove(end + 1, expEnd)
}

Expand Down Expand Up @@ -538,7 +545,12 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {
}

// normalize
const [url, resolvedId] = await normalizeUrl(specifier, start)
const [url, resolvedId] = await normalizeUrl(
specifier,
start,
undefined,
importAttributes,
)

// record as safe modules
// safeModulesPath should not include the base prefix.
Expand Down
7 changes: 0 additions & 7 deletions packages/vite/src/node/plugins/importAnalysisBuild.ts
Original file line number Diff line number Diff line change
Expand Up @@ -304,20 +304,13 @@ export function buildImportAnalysisPlugin(config: ResolvedConfig): Plugin {
for (let index = 0; index < imports.length; index++) {
const {
s: start,
e: end,
ss: expStart,
se: expEnd,
d: dynamicIndex,
a: attributeIndex,
} = imports[index]

const isDynamicImport = dynamicIndex > -1

// strip import attributes as we can process them ourselves
if (!isDynamicImport && attributeIndex > -1) {
str().remove(end + 1, expEnd)
}

if (
isDynamicImport &&
insertPreload &&
Expand Down
4 changes: 4 additions & 0 deletions playground/resolve/__tests__/resolve.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,10 @@ test('Resolving from other package with imports field', async () => {
expect(await page.textContent('.imports-pkg-slash')).toMatch('[success]')
})

test('Resolving import attributes', async () => {
expect(await page.textContent('.import-attributes')).toMatch('[success]')
})

test('Resolving with query with imports field', async () => {
// since it is imported with `?url` it should return a URL
expect(await page.textContent('.imports-query')).toMatch(
Expand Down
3 changes: 3 additions & 0 deletions playground/resolve/import-attributes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { msg as importAttributes } from '@virtual-file-import-attributes' with { foo: 'bar', baz: 'qux' }

export const msg = importAttributes
6 changes: 6 additions & 0 deletions playground/resolve/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,9 @@ <h2>resolve package that contains # in path</h2>
<h2>resolve non normalized absolute path</h2>
<p class="non-normalized"></p>

<h2>Resolving import attributes</h2>
<p class="import-attributes">fail</p>

<script type="module">
import '@generated-content-virtual-file'
function text(selector, text) {
Expand Down Expand Up @@ -396,6 +399,9 @@ <h2>resolve non normalized absolute path</h2>

import nonNormalizedAbsolute from '@non-normalized'
text('.non-normalized', nonNormalizedAbsolute)

import { msg as importAttributes } from './import-attributes'
text('.import-attributes', importAttributes)
</script>

<style>
Expand Down
25 changes: 25 additions & 0 deletions playground/resolve/vite.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ const virtualId9036 = '\0' + virtualFile9036

const customVirtualFile = '@custom-virtual-file'

const virtualFileImportAttributes = '@virtual-file-import-attributes'
const virtualIdImportAttributes = '\0' + virtualFileImportAttributes
let importAttributes = {}

const generatedContentVirtualFile = '@generated-content-virtual-file'
const generatedContentImports = [
{
Expand Down Expand Up @@ -106,6 +110,27 @@ export default defineConfig({
return this.resolve(__dirname + '//non-normalized')
},
},
{
name: 'import-attributes',
resolveId(id, _, options) {
if (id === virtualFileImportAttributes) {
importAttributes = options.attributes
return virtualIdImportAttributes
}
},
load(id) {
if (id === virtualIdImportAttributes) {
if (
importAttributes.foo === 'bar' &&
importAttributes.baz === 'qux'
) {
return `export const msg = "[success] from virtual import attribute"`
} else {
return `export const msg = "fail"`
}
}
},
},
],
optimizeDeps: {
include: [
Expand Down

0 comments on commit 90f685b

Please sign in to comment.