Skip to content

Commit

Permalink
refactor: improve regexp performance (#27207)
Browse files Browse the repository at this point in the history
  • Loading branch information
antfu committed May 14, 2024
1 parent 7189daf commit b96b62e
Show file tree
Hide file tree
Showing 36 changed files with 113 additions and 61 deletions.
4 changes: 4 additions & 0 deletions eslint.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import noOnlyTests from 'eslint-plugin-no-only-tests'
import typegen from 'eslint-typegen'
// @ts-expect-error missing types
import perfectionist from 'eslint-plugin-perfectionist'
import regex from 'eslint-plugin-regexp'

export default createConfigForNuxt({
features: {
Expand Down Expand Up @@ -216,6 +217,9 @@ export default createConfigForNuxt({
'vue/multi-word-component-names': 'off',
},
},

// @ts-ignore types misaligned
regex.configs['flat/recommended'],
)

// Generate type definitions for the eslint config
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@
"eslint": "9.2.0",
"eslint-plugin-no-only-tests": "3.1.0",
"eslint-plugin-perfectionist": "2.10.0",
"eslint-plugin-regexp": "^2.5.0",
"eslint-typegen": "0.2.4",
"execa": "9.1.0",
"fs-extra": "11.2.0",
Expand Down
2 changes: 1 addition & 1 deletion packages/kit/src/compatibility.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import type { Nuxt, NuxtCompatibility, NuxtCompatibilityIssues } from '@nuxt/sch
import { useNuxt } from './context'

export function normalizeSemanticVersion (version: string) {
return version.replace(/-[0-9]+\.[0-9a-f]+/, '') // Remove edge prefix
return version.replace(/-\d+\.[0-9a-f]+/, '') // Remove edge prefix
}

const builderMap = {
Expand Down
2 changes: 1 addition & 1 deletion packages/kit/src/internal/template.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export async function compileTemplate<T> (template: NuxtTemplate<T>, ctx: any) {
}

/** @deprecated */
const serialize = (data: any) => JSON.stringify(data, null, 2).replace(/"{(.+)}"(?=,?$)/gm, r => JSON.parse(r).replace(/^{(.*)}$/, '$1'))
const serialize = (data: any) => JSON.stringify(data, null, 2).replace(/"\{(.+)\}"(?=,?$)/gm, r => JSON.parse(r).replace(/^\{(.*)\}$/, '$1'))

/** @deprecated */
const importSources = (sources: string | string[], { lazy = false } = {}) => {
Expand Down
2 changes: 1 addition & 1 deletion packages/kit/src/runtime-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ function applyEnv (
return obj
}

const envExpandRx = /{{(.*?)}}/g
const envExpandRx = /\{\{(.*?)\}\}/g

function _expandFromEnv (value: string, env: Record<string, any> = process.env) {
return value.replace(envExpandRx, (match, key) => {
Expand Down
4 changes: 2 additions & 2 deletions packages/kit/src/template.ts
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ export async function _generateTypes (nuxt: Nuxt) {
} else {
const path = stats?.isFile()
// remove extension
? relativePath.replace(/(?<=\w)\.\w+$/g, '')
? relativePath.replace(/\b\.\w+$/g, '')
// non-existent file probably shouldn't be resolved
: aliases[alias]

Expand Down Expand Up @@ -230,7 +230,7 @@ export async function _generateTypes (nuxt: Nuxt) {
tsConfig.compilerOptions!.paths[alias] = await Promise.all(paths.map(async (path: string) => {
if (!isAbsolute(path)) { return path }
const stats = await fsp.stat(path).catch(() => null /* file does not exist */)
return relativeWithDot(nuxt.options.buildDir, stats?.isFile() ? path.replace(/(?<=\w)\.\w+$/g, '') /* remove extension */ : path)
return relativeWithDot(nuxt.options.buildDir, stats?.isFile() ? path.replace(/\b\.\w+$/g, '') /* remove extension */ : path)
}))
}

Expand Down
4 changes: 2 additions & 2 deletions packages/nuxt/src/components/client-fallback-auto-id.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ interface LoaderOptions {
transform?: ComponentsOptions['transform']
rootDir: string
}
const CLIENT_FALLBACK_RE = /<(NuxtClientFallback|nuxt-client-fallback)( [^>]*)?>/
const CLIENT_FALLBACK_RE = /<(?:NuxtClientFallback|nuxt-client-fallback)(?: [^>]*)?>/
const CLIENT_FALLBACK_GLOBAL_RE = /<(NuxtClientFallback|nuxt-client-fallback)( [^>]*)?>/g
export const clientFallbackAutoIdPlugin = createUnplugin((options: LoaderOptions) => {
const exclude = options.transform?.exclude || []
Expand All @@ -37,7 +37,7 @@ export const clientFallbackAutoIdPlugin = createUnplugin((options: LoaderOptions

s.replace(CLIENT_FALLBACK_GLOBAL_RE, (full, name, attrs) => {
count++
if (/ :?uid=/g.test(attrs)) { return full }
if (/ :?uid=/.test(attrs)) { return full }
return `<${name} :uid="'${hash(relativeID)}' + JSON.stringify($props) + '${count}'" ${attrs ?? ''}>`
})

Expand Down
2 changes: 1 addition & 1 deletion packages/nuxt/src/components/islandsTransform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ interface ComponentChunkOptions {
}

const SCRIPT_RE = /<script[^>]*>/g
const HAS_SLOT_OR_CLIENT_RE = /(<slot[^>]*>)|(nuxt-client)/
const HAS_SLOT_OR_CLIENT_RE = /<slot[^>]*>|nuxt-client/
const TEMPLATE_RE = /<template>([\s\S]*)<\/template>/
const NUXTCLIENT_ATTR_RE = /\s:?nuxt-client(="[^"]*")?/g
const IMPORT_CODE = '\nimport { vforToArray as __vforToArray } from \'#app/components/utils\'' + '\nimport NuxtTeleportIslandComponent from \'#app/components/nuxt-teleport-island-component\'' + '\nimport NuxtTeleportSsrSlot from \'#app/components/nuxt-teleport-island-slot\''
Expand Down
2 changes: 1 addition & 1 deletion packages/nuxt/src/components/loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ export const loaderPlugin = createUnplugin((options: LoaderOptions) => {
const s = new MagicString(code)

// replace `_resolveComponent("...")` to direct import
s.replace(/(?<=[ (])_?resolveComponent\(\s*["'](lazy-|Lazy)?([^'"]*?)["'][\s,]*[^)]*\)/g, (full: string, lazy: string, name: string) => {
s.replace(/(?<=[ (])_?resolveComponent\(\s*["'](lazy-|Lazy)?([^'"]*)["'][^)]*\)/g, (full: string, lazy: string, name: string) => {
const component = findComponent(components, name, options.mode)
if (component) {
// @ts-expect-error TODO: refactor to nuxi
Expand Down
2 changes: 1 addition & 1 deletion packages/nuxt/src/components/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ function compareDirByPathLength ({ path: pathA }: { path: string }, { path: path
return pathB.split(/[\\/]/).filter(Boolean).length - pathA.split(/[\\/]/).filter(Boolean).length
}

const DEFAULT_COMPONENTS_DIRS_RE = /\/components(\/global|\/islands)?$/
const DEFAULT_COMPONENTS_DIRS_RE = /\/components\/(?:global|islands)?$/

export type getComponentsT = (mode?: 'client' | 'server' | 'all') => Component[]

Expand Down
4 changes: 2 additions & 2 deletions packages/nuxt/src/components/scan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,8 @@ export async function scanComponents (dirs: ComponentsDir[], srcDir: string): Pr
*/
let fileName = basename(filePath, extname(filePath))

const island = /\.(island)(\.global)?$/.test(fileName) || dir.island
const global = /\.(global)(\.island)?$/.test(fileName) || dir.global
const island = /\.island(?:\.global)?$/.test(fileName) || dir.island
const global = /\.global(?:\.island)?$/.test(fileName) || dir.global
const mode = island ? 'server' : (fileName.match(/(?<=\.)(client|server)(\.global|\.island)*$/)?.[1] || 'all') as 'client' | 'server' | 'all'
fileName = fileName.replace(/(\.(client|server))?(\.global|\.island)*$/, '')

Expand Down
4 changes: 2 additions & 2 deletions packages/nuxt/src/components/templates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,8 @@ export const componentsTypeTemplate = {
const buildDir = nuxt.options.buildDir
const componentTypes = app.components.filter(c => !c.island).map((c) => {
const type = `typeof ${genDynamicImport(isAbsolute(c.filePath)
? relative(buildDir, c.filePath).replace(/(?<=\w)\.(?!vue)\w+$/g, '')
: c.filePath.replace(/(?<=\w)\.(?!vue)\w+$/g, ''), { wrapper: false })}['${c.export}']`
? relative(buildDir, c.filePath).replace(/\b\.(?!vue)\w+$/g, '')
: c.filePath.replace(/\b\.(?!vue)\w+$/g, ''), { wrapper: false })}['${c.export}']`
return [
c.pascalName,
c.island || c.mode === 'server' ? `IslandComponent<${type}>` : type,
Expand Down
2 changes: 1 addition & 1 deletion packages/nuxt/src/components/tree-shake.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ interface TreeShakeTemplatePluginOptions {
type AcornNode<N extends Node> = N & { start: number, end: number }

const SSR_RENDER_RE = /ssrRenderComponent/
const PLACEHOLDER_EXACT_RE = /^(fallback|placeholder)$/
const PLACEHOLDER_EXACT_RE = /^(?:fallback|placeholder)$/
const CLIENT_ONLY_NAME_RE = /^(?:_unref\()?(?:_component_)?(?:Lazy|lazy_)?(?:client_only|ClientOnly\)?)$/
const PARSER_OPTIONS = { sourceType: 'module', ecmaVersion: 'latest' }

Expand Down
2 changes: 1 addition & 1 deletion packages/nuxt/src/core/builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export async function build (nuxt: Nuxt) {
if (event === 'change') { return }
const path = resolve(nuxt.options.srcDir, relativePath)
const relativePaths = nuxt.options._layers.map(l => relative(l.config.srcDir || l.cwd, path))
const restartPath = relativePaths.find(relativePath => /^(app\.|error\.|plugins\/|middleware\/|layouts\/)/i.test(relativePath))
const restartPath = relativePaths.find(relativePath => /^(?:app\.|error\.|plugins\/|middleware\/|layouts\/)/i.test(relativePath))
if (restartPath) {
if (restartPath.startsWith('app')) {
app.mainComponent = undefined
Expand Down
2 changes: 1 addition & 1 deletion packages/nuxt/src/core/nitro.ts
Original file line number Diff line number Diff line change
Expand Up @@ -383,7 +383,7 @@ export async function initNitro (nuxt: Nuxt & { _nitro?: Nitro }) {
tsConfig.compilerOptions.paths[alias] = [absolutePath]
tsConfig.compilerOptions.paths[`${alias}/*`] = [`${absolutePath}/*`]
} else {
tsConfig.compilerOptions.paths[alias] = [absolutePath.replace(/(?<=\w)\.\w+$/g, '')] /* remove extension */
tsConfig.compilerOptions.paths[alias] = [absolutePath.replace(/\b\.\w+$/g, '')] /* remove extension */
}
}

Expand Down
2 changes: 1 addition & 1 deletion packages/nuxt/src/core/nuxt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -621,4 +621,4 @@ export async function loadNuxt (opts: LoadNuxtOptions): Promise<Nuxt> {
return nuxt
}

const RESTART_RE = /^(app|error|app\.config)\.(js|ts|mjs|jsx|tsx|vue)$/i
const RESTART_RE = /^(?:app|error|app\.config)\.(?:js|ts|mjs|jsx|tsx|vue)$/i
2 changes: 1 addition & 1 deletion packages/nuxt/src/core/plugins/import-protection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export const nuxtImportProtections = (nuxt: { options: NuxtOptions }, options: {
])

patterns.push([
/^((|~|~~|@|@@)\/)?nuxt\.config(\.|$)/,
/^((~|~~|@|@@)?\/)?nuxt\.config(\.|$)/,
'Importing directly from a `nuxt.config` file is not allowed. Instead, use runtime config or a module.',
])

Expand Down
4 changes: 2 additions & 2 deletions packages/nuxt/src/core/runtime/nitro/dev-server-logs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,8 @@ function getStack () {
return stack.stack?.replace(EXCLUDE_TRACE_RE, '').replace(/^Error.*\n/, '') || ''
}

const FILENAME_RE = /at.*\(([^:)]+)[):]/
const FILENAME_RE_GLOBAL = /at.*\(([^)]+)\)/g
const FILENAME_RE = /at[^(]*\(([^:)]+)[):]/
const FILENAME_RE_GLOBAL = /at[^(]*\(([^)]+)\)/g
function extractFilenameFromStack (stacktrace: string) {
return stacktrace.match(FILENAME_RE)?.[1].replace(withTrailingSlash(rootDir), '')
}
Expand Down
2 changes: 1 addition & 1 deletion packages/nuxt/src/core/runtime/nitro/renderer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -646,7 +646,7 @@ function getServerComponentHTML (body: string[]): string {

const SSR_SLOT_TELEPORT_MARKER = /^uid=([^;]*);slot=(.*)$/
const SSR_CLIENT_TELEPORT_MARKER = /^uid=([^;]*);client=(.*)$/
const SSR_CLIENT_SLOT_MARKER = /^island-slot=(?:[^;]*);(.*)$/
const SSR_CLIENT_SLOT_MARKER = /^island-slot=[^;]*;(.*)$/

function getSlotIslandResponse (ssrContext: NuxtSSRContext): NuxtIslandResponse['slots'] {
if (!ssrContext.islandContext || !Object.keys(ssrContext.islandContext.slots).length) { return undefined }
Expand Down
2 changes: 1 addition & 1 deletion packages/nuxt/src/core/templates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,7 @@ export const appConfigDeclarationTemplate: NuxtTemplate = {
return `
import type { CustomAppConfig } from 'nuxt/schema'
import type { Defu } from 'defu'
${app.configs.map((id: string, index: number) => `import ${`cfg${index}`} from ${JSON.stringify(id.replace(/(?<=\w)\.\w+$/g, ''))}`).join('\n')}
${app.configs.map((id: string, index: number) => `import ${`cfg${index}`} from ${JSON.stringify(id.replace(/\b\.\w+$/g, ''))}`).join('\n')}
declare const inlineConfig = ${JSON.stringify(nuxt.options.appConfig, null, 2)}
type ResolvedAppConfig = Defu<typeof inlineConfig, [${app.configs.map((_id: string, index: number) => `typeof cfg${index}`).join(', ')}]>
Expand Down
2 changes: 1 addition & 1 deletion packages/nuxt/src/core/utils/plugins.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export function isVue (id: string, opts: { type?: Array<'template' | 'script' |
return true
}

const JS_RE = /\.((c|m)?j|t)sx?$/
const JS_RE = /\.(?:[cm]?j|t)sx?$/

export function isJS (id: string) {
// JavaScript files
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export default defineNuxtPlugin(async () => {

// Implementation

const OPTIONAL_PARAM_RE = /^\/?:.*(\?|\(\.\*\)\*)$/
const OPTIONAL_PARAM_RE = /^\/?:.*(?:\?|\(\.\*\)\*)$/

function processRoutes (routes: RouteRecordRaw[], currentPath = '/', routesToPrerender = new Set<string>()) {
for (const route of routes) {
Expand Down
8 changes: 4 additions & 4 deletions packages/nuxt/src/pages/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ export async function generateRoutesFromFiles (files: ScannedFile[], options: Ge
return prepareRoutes(routes)
}

const SFC_SCRIPT_RE = /<script\s*[^>]*>([\s\S]*?)<\/script\s*[^>]*>/i
const SFC_SCRIPT_RE = /<script[^>]*>([\s\S]*?)<\/script[^>]*>/i
export function extractScriptContent (html: string) {
const match = html.match(SFC_SCRIPT_RE)

Expand All @@ -146,7 +146,7 @@ export function extractScriptContent (html: string) {
return null
}

const PAGE_META_RE = /(definePageMeta\([\s\S]*?\))/
const PAGE_META_RE = /definePageMeta\([\s\S]*?\)/
const DYNAMIC_META_KEY = '__nuxt_dynamic_meta_key' as const

const pageContentsCache: Record<string, string> = {}
Expand Down Expand Up @@ -261,7 +261,7 @@ function getRoutePath (tokens: SegmentToken[]): string {
}, '/')
}

const PARAM_CHAR_RE = /[\w\d_.]/
const PARAM_CHAR_RE = /[\w.]/

function parseSegment (segment: string) {
let state: SegmentParserState = SegmentParserState.initial
Expand Down Expand Up @@ -537,7 +537,7 @@ export function pathToNitroGlob (path: string) {
return null
}

return path.replace(/\/(?:[^:/]+)?:\w+.*$/, '/**')
return path.replace(/\/[^:/]*:\w.*$/, '/**')
}

export function resolveRoutePaths (page: NuxtPage, parent = '/'): string[] {
Expand Down
2 changes: 1 addition & 1 deletion packages/nuxt/test/treeshake-client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ describe('treeshake client only in ssr', () => {
expect(treeshaken).not.toContain('ssrRenderComponent(_unref(HelloWorld')
expect(treeshaken).toContain('ssrRenderComponent(_unref(Glob')
}
expect(treeshaken.replace(/data-v-[\d\w]{8}/g, 'data-v-one-hash').replace(/scoped=[\d\w]{8}/g, 'scoped=one-hash')).toMatchSnapshot()
expect(treeshaken.replace(/data-v-\w{8}/g, 'data-v-one-hash').replace(/scoped=\w{8}/g, 'scoped=one-hash')).toMatchSnapshot()
})
}

Expand Down
2 changes: 1 addition & 1 deletion packages/ui-templates/lib/dev.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export const DevRenderingPlugin = () => {
const messages = JSON.parse(await fsp.readFile(r(page, 'messages.json'), 'utf-8'))

return template(contents, {
interpolate: /{{{?([\s\S]+?)}?}}/g,
interpolate: /\{\{\{?([\s\S]+?)\}?\}\}/g,
})({
messages: { ...genericMessages, ...messages },
})
Expand Down
22 changes: 11 additions & 11 deletions packages/ui-templates/lib/render.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ export const RenderPlugin = () => {
}

// Inline our scripts
const scriptSources = Array.from(html.matchAll(/<script[^>]*src="(.*)"[^>]*>[\s\S]*?<\/script>/g))
const scriptSources = Array.from(html.matchAll(/<script[^>]*src="([^"]*)"[^>]*>[\s\S]*?<\/script>/g))
.filter(([_block, src]) => src?.match(/^\/.*\.js$/))

for (const [scriptBlock, src] of scriptSources) {
Expand All @@ -79,10 +79,10 @@ export const RenderPlugin = () => {
const messages = JSON.parse(readFileSync(r(`templates/${templateName}/messages.json`), 'utf-8'))

// Serialize into a js function
const chunks = html.split(/\{{2,3}\s*[^{}]+\s*\}{2,3}/g).map(chunk => JSON.stringify(chunk))
const chunks = html.split(/\{{2,3}[^{}]+\}{2,3}/g).map(chunk => JSON.stringify(chunk))
const hasMessages = chunks.length > 1
let templateString = chunks.shift()
for (const expression of html.matchAll(/\{{2,3}(\s*[^{}]+\s*)\}{2,3}/g)) {
for (const expression of html.matchAll(/\{{2,3}([^{}]+)\}{2,3}/g)) {
templateString += ` + (${expression[1].trim()}) + ${chunks.shift()}`
}
if (chunks.length > 0) {
Expand All @@ -98,28 +98,28 @@ export const RenderPlugin = () => {
].join('\n')

const templateContent = html
.match(/<body.*?>([\s\S]*)<\/body>/)?.[0]
.replace(/(?<=<|<\/)body/g, 'div')
.match(/<body[^>]*>([\s\S]*)<\/body>/)?.[0]
.replace(/(?<=<\/|<)body/g, 'div')
.replace(/messages\./g, '')
.replace(/<script[^>]*>([\s\S]*?)<\/script>/g, '')
.replace(/<a href="(\/[^"]*)"([^>]*)>([\s\S]*)<\/a>/g, '<NuxtLink to="$1"$2>\n$3\n</NuxtLink>')

.replace(/<([^>]+) ([a-z]+)="([^"]*)({{\s*(\w+?)\s*}})([^"]*)"([^>]*)>/g, '<$1 :$2="`$3${$5}$6`"$7>')
.replace(/>{{\s*(\w+?)\s*}}<\/[\w-]*>/g, ' v-text="$1" />')
.replace(/>{{{\s*(\w+?)\s*}}}<\/[\w-]*>/g, ' v-html="$1" />')
.replace(/<([^>]+) ([a-z]+)="([^"]*)(\{\{\s*(\w+)\s*\}\})([^"]*)"([^>]*)>/g, '<$1 :$2="`$3${$5}$6`"$7>')
.replace(/>\{\{\s*(\w+)\s*\}\}<\/[\w-]*>/g, ' v-text="$1" />')
.replace(/>\{\{\{\s*(\w+)\s*\}\}\}<\/[\w-]*>/g, ' v-html="$1" />')
// We are not matching <link> <script> and <meta> tags as these aren't used yet in nuxt/ui
// and should be taken care of wherever this SFC is used
const title = html.match(/<title.*?>([\s\S]*)<\/title>/)?.[1].replace(/{{([\s\S]+?)}}/g, (r) => {
const title = html.match(/<title[^>]*>([\s\S]*)<\/title>/)?.[1].replace(/\{\{([\s\S]+?)\}\}/g, (r) => {
return `\${${r.slice(2, -2)}}`.replace(/messages\./g, 'props.')
})
const styleContent = Array.from(html.matchAll(/<style[^>]*>([\s\S]*?)<\/style>/g)).map(block => block[1]).join('\n')
const globalStyles = styleContent.replace(/(\.[^{\d][^{]*?\{[^}]*?\})+.?/g, (r) => {
const globalStyles = styleContent.replace(/(\.[^{\d][^{]*\{[^}]*\})+.?/g, (r) => {
const lastChar = r[r.length - 1]
if (lastChar && !['}', '.', '@', '*', ':'].includes(lastChar)) {
return ';' + lastChar
}
return lastChar
}).replace(/@media[^{]*?\{\}/g, '')
}).replace(/@media[^{]*\{\}/g, '')
const inlineScripts = Array.from(html.matchAll(/<script>([\s\S]*?)<\/script>/g))
.map(block => block[1])
.filter(i => !i.includes('const t=document.createElement("link")'))
Expand Down
6 changes: 3 additions & 3 deletions packages/vite/src/plugins/composable-keys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ interface ComposableKeysOptions {
}

const stringTypes = ['Literal', 'TemplateLiteral']
const NUXT_LIB_RE = /node_modules\/(nuxt|nuxt3|nuxt-nightly)\//
const SUPPORTED_EXT_RE = /\.(m?[jt]sx?|vue)/
const NUXT_LIB_RE = /node_modules\/(?:nuxt|nuxt3|nuxt-nightly)\//
const SUPPORTED_EXT_RE = /\.(?:m?[jt]sx?|vue)/

export const composableKeysPlugin = createUnplugin((options: ComposableKeysOptions) => {
const composableMeta: Record<string, any> = {}
Expand All @@ -40,7 +40,7 @@ export const composableKeysPlugin = createUnplugin((options: ComposableKeysOptio
},
transform (code, id) {
if (!KEYED_FUNCTIONS_RE.test(code)) { return }
const { 0: script = code, index: codeIndex = 0 } = code.match(/(?<=<script[^>]*>)[\S\s.]*?(?=<\/script>)/) || { index: 0, 0: code }
const { 0: script = code, index: codeIndex = 0 } = code.match(/(?<=<script[^>]*>)[\s\S]*?(?=<\/script>)/) || { index: 0, 0: code }
const s = new MagicString(code)
// https://github.com/unjs/unplugin/issues/90
let imports: Set<string> | undefined
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/plugins/ssr-styles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ interface SSRStylePluginOptions {
mode: 'server' | 'client'
}

const SUPPORTED_FILES_RE = /\.(vue|((c|m)?j|t)sx?)$/
const SUPPORTED_FILES_RE = /\.(?:vue|(?:[cm]?j|t)sx?)$/

export function ssrStylesPlugin (options: SSRStylePluginOptions): Plugin {
const cssMap: Record<string, { files: string[], inBundle: boolean }> = {}
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ export function uniq<T> (arr: T[]): T[] {
}

// Copied from vue-bundle-renderer utils
const IS_CSS_RE = /\.(?:css|scss|sass|postcss|pcss|less|stylus|styl)(\?[^.]+)?$/
const IS_CSS_RE = /\.(?:css|scss|sass|postcss|pcss|less|stylus|styl)(?:\?[^.]+)?$/

export function isCSS (file: string) {
return IS_CSS_RE.test(file)
Expand Down
2 changes: 1 addition & 1 deletion packages/webpack/src/configs/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { applyPresets } from '../utils/config'
import { nuxt } from '../presets/nuxt'
import { node } from '../presets/node'

const assetPattern = /\.(css|s[ca]ss|png|jpe?g|gif|svg|woff2?|eot|ttf|otf|webp|webm|mp4|ogv)(\?.*)?$/i
const assetPattern = /\.(?:css|s[ca]ss|png|jpe?g|gif|svg|woff2?|eot|ttf|otf|webp|webm|mp4|ogv)(?:\?.*)?$/i

export function server (ctx: WebpackConfigContext) {
ctx.name = 'server'
Expand Down
2 changes: 1 addition & 1 deletion packages/webpack/src/plugins/vue/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,6 @@ export const isJS = (file: string) => isJSRegExp.test(file)

export const extractQueryPartJS = (file: string) => isJSRegExp.exec(file)?.[1]

export const isCSS = (file: string) => /\.css(\?[^.]+)?$/.test(file)
export const isCSS = (file: string) => /\.css(?:\?[^.]+)?$/.test(file)

export const isHotUpdate = (file: string) => file.includes('hot-update')

0 comments on commit b96b62e

Please sign in to comment.