Skip to content

Commit

Permalink
fix: deprecate { assert: { type: raw }} in favor of { as: raw } (fix
Browse files Browse the repository at this point in the history
  • Loading branch information
brillout committed Mar 8, 2022
1 parent 5648d09 commit 87ecce5
Show file tree
Hide file tree
Showing 7 changed files with 51 additions and 22 deletions.
4 changes: 2 additions & 2 deletions docs/guide/features.md
Expand Up @@ -298,10 +298,10 @@ const modules = {
}
```

`import.meta.glob` and `import.meta.globEager` also support importing files as strings, similar to [Importing Asset as String](https://vitejs.dev/guide/assets.html#importing-asset-as-string). Here, we use the [Import Assertions](https://github.com/tc39/proposal-import-assertions#synopsis) syntax to import.
`import.meta.glob` and `import.meta.globEager` also support importing files as strings (similar to [Importing Asset as String](https://vitejs.dev/guide/assets.html#importing-asset-as-string)) with the [Import Reflection](https://github.com/tc39/proposal-import-reflection) syntax:

```js
const modules = import.meta.glob('./dir/*.js', { assert: { type: 'raw' } })
const modules = import.meta.glob('./dir/*.js', { as: 'raw' })
```

The above will be transformed into the following:
Expand Down
2 changes: 1 addition & 1 deletion packages/playground/glob-import/index.html
Expand Up @@ -40,7 +40,7 @@

<script type="module">
const rawModules = import.meta.globEager('/dir/*.json', {
assert: { type: 'raw' }
as: 'raw'
})
const globraw = {}
Object.keys(rawModules).forEach((key) => {
Expand Down
37 changes: 28 additions & 9 deletions packages/vite/src/node/importGlob.ts
Expand Up @@ -16,6 +16,8 @@ import {
normalizePath
} from './utils'
import type { RollupError } from 'rollup'
import type { Logger } from '.'
import colors from 'picocolors'

interface GlobParams {
base: string
Expand All @@ -24,7 +26,11 @@ interface GlobParams {
isAbsolute: boolean
}

export interface AssertOptions {
interface GlobOptions {
as?: string
/**
* @deprecated
*/
assert?: {
type: string
}
Expand All @@ -50,6 +56,7 @@ export async function transformImportGlob(
importer: string,
importIndex: number,
root: string,
logger: Logger,
normalizeUrl?: (url: string, pos: number) => Promise<[string, string]>,
resolve?: (url: string, importer?: string) => Promise<string | undefined>,
preload = true
Expand All @@ -75,7 +82,7 @@ export async function transformImportGlob(
importer = cleanUrl(importer)
const importerBasename = path.basename(importer)

const [userPattern, assertion, endIndex] = lexGlobPattern(source, pos)
const [userPattern, options, endIndex] = lexGlobPattern(source, pos)

let globParams: GlobParams | null = null
if (userPattern.startsWith('/')) {
Expand Down Expand Up @@ -126,7 +133,19 @@ export async function transformImportGlob(
;[importee] = await normalizeUrl(file, pos)
}
imports.push(importee)
if (assertion?.assert?.type === 'raw') {
// TODO remove assert syntax for the Vite 3.0 release.
const isRawAssert = options?.assert?.type === 'raw'
const isRawType = options?.as === 'raw'
if (isRawType || isRawAssert) {
if (isRawAssert) {
logger.warn(
colors.yellow(
colors.bold(
"(!) import.meta.glob('...', { assert: { type: 'raw' }}) is deprecated. Use import.meta.glob('...', { as: 'raw' }) instead."
)
)
)
}
entries += ` ${JSON.stringify(file)}: ${JSON.stringify(
await fsp.readFile(path.join(base, file), 'utf-8')
)},`
Expand Down Expand Up @@ -173,7 +192,7 @@ const enum LexerState {
function lexGlobPattern(
code: string,
pos: number
): [string, AssertOptions, number] {
): [string, GlobOptions, number] {
let state = LexerState.inCall
let pattern = ''

Expand Down Expand Up @@ -225,14 +244,14 @@ function lexGlobPattern(
.replace(multilineCommentsRE, blankReplacer)

const endIndex = noCommentCode.indexOf(')')
const options = noCommentCode.substring(0, endIndex)
const commaIndex = options.indexOf(',')
const optionString = noCommentCode.substring(0, endIndex)
const commaIndex = optionString.indexOf(',')

let assert = {}
let options = {}
if (commaIndex > -1) {
assert = JSON5.parse(options.substring(commaIndex + 1))
options = JSON5.parse(optionString.substring(commaIndex + 1))
}
return [pattern, assert, endIndex + i + 2]
return [pattern, options, endIndex + i + 2]
}

function error(pos: number) {
Expand Down
12 changes: 8 additions & 4 deletions packages/vite/src/node/optimizer/scan.ts
@@ -1,7 +1,7 @@
import fs from 'fs'
import path from 'path'
import glob from 'fast-glob'
import type { ResolvedConfig } from '..'
import type { ResolvedConfig, Logger } from '..'
import type { Loader, Plugin, OnLoadResult } from 'esbuild'
import { build, transform } from 'esbuild'
import {
Expand Down Expand Up @@ -296,7 +296,8 @@ function esbuildScanPlugin(
path,
config.root,
loader,
resolve
resolve,
config.logger
)
}
} else {
Expand Down Expand Up @@ -454,7 +455,8 @@ function esbuildScanPlugin(
id,
config.root,
ext as Loader,
resolve
resolve,
config.logger
).then((contents) => ({
loader: ext as Loader,
contents
Expand All @@ -474,7 +476,8 @@ async function transformGlob(
importer: string,
root: string,
loader: Loader,
resolve: (url: string, importer?: string) => Promise<string | undefined>
resolve: (url: string, importer?: string) => Promise<string | undefined>,
logger: Logger
) {
// transform the content first since es-module-lexer can't handle non-js
if (loader !== 'js') {
Expand All @@ -495,6 +498,7 @@ async function transformGlob(
normalizePath(importer),
index,
root,
logger,
undefined,
resolve
)
Expand Down
1 change: 1 addition & 0 deletions packages/vite/src/node/plugins/importAnalysis.ts
Expand Up @@ -355,6 +355,7 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {
importer,
index,
root,
config.logger,
normalizeUrl,
resolve
)
Expand Down
1 change: 1 addition & 0 deletions packages/vite/src/node/plugins/importAnalysisBuild.ts
Expand Up @@ -158,6 +158,7 @@ export function buildImportAnalysisPlugin(config: ResolvedConfig): Plugin {
importer,
index,
config.root,
config.logger,
undefined,
resolve,
insertPreload
Expand Down
16 changes: 10 additions & 6 deletions packages/vite/types/importMeta.d.ts
Expand Up @@ -4,10 +4,14 @@

/* eslint-disable @typescript-eslint/consistent-type-imports */

// Duplicate import('../src/node/importGlob').AssertOptions
// Avoid breaking the production client type because this file is referenced
// in vite/client.d.ts and in production src/node/importGlob.ts doesn't exist
interface AssertOptions {
// Duplicate of import('../src/node/importGlob').GlobOptions in order to
// avoid breaking the production client type. Because this file is referenced
// in vite/client.d.ts and in production src/node/importGlob.ts doesn't exist.
interface GlobOptions {
as?: string
/**
* @deprecated
*/
assert?: {
type: string
}
Expand Down Expand Up @@ -61,12 +65,12 @@ interface ImportMeta {

glob<Module = { [key: string]: any }>(
pattern: string,
options?: AssertOptions
options?: GlobOptions
): Record<string, () => Promise<Module>>

globEager<Module = { [key: string]: any }>(
pattern: string,
options?: AssertOptions
options?: GlobOptions
): Record<string, Module>
}

Expand Down

0 comments on commit 87ecce5

Please sign in to comment.