Skip to content
This repository has been archived by the owner on Apr 6, 2023. It is now read-only.

Commit

Permalink
refactor: use mlly utilities
Browse files Browse the repository at this point in the history
  • Loading branch information
danielroe committed Nov 30, 2021
1 parent 3277488 commit 49fd805
Show file tree
Hide file tree
Showing 17 changed files with 77 additions and 72 deletions.
13 changes: 5 additions & 8 deletions packages/bridge/src/vite/templates.ts
Expand Up @@ -2,6 +2,7 @@ import hash from 'hash-sum'
import { resolve } from 'pathe'

import type { Nuxt, NuxtApp } from '@nuxt/schema'
import { genImport, genObjectFromRawEntries } from 'mlly'

type TemplateContext = {
nuxt: Nuxt;
Expand All @@ -18,10 +19,8 @@ export const middlewareTemplate = {
filePath: resolve(srcDir, dir.middleware, m.src),
id: m.name || m.src.replace(/[\\/]/g, '/').replace(/\.(js|ts)$/, '')
}))
return `${_middleware.map(m => `import $${hash(m.id)} from ${JSON.stringify(m.filePath)}`).join('\n')}
const middleware = {
${_middleware.map(m => ` [${JSON.stringify(m.id)}]: $${hash(m.id)}`).join(',\n')}
}
return `${_middleware.map(m => genImport(m.filePath, `$${hash(m.id)}`)).join('\n')}
const middleware = ${genObjectFromRawEntries(_middleware.map(m => [m.id, `$${hash(m.id)}`]))}
export default middleware`
}
}
Expand All @@ -43,14 +42,12 @@ export const storeTemplate = {

return `import Vue from 'vue'
import Vuex from 'vuex'
${_storeModules.map(s => `import * as $${hash(s.id)} from ${JSON.stringify(s.filePath)}`).join('\n')}
${_storeModules.map(s => genImport(s.filePath, { name: '*', as: `$${hash(s.id)}` })).join('\n')}
Vue.use(Vuex)
const VUEX_PROPERTIES = ['state', 'getters', 'actions', 'mutations']
const storeModules = {
${_storeModules.map(m => ` [${JSON.stringify(m.id)}]: $${hash(m.id)}`).join(',\n')}
}
const storeModules = ${genObjectFromRawEntries(_storeModules.map(m => [m.id, `$${hash(m.id)}`]))}
export function createStore() {
let store = normalizeRoot(storeModules.root || {})
Expand Down
3 changes: 2 additions & 1 deletion packages/kit/src/components.ts
@@ -1,5 +1,6 @@
import { pascalCase, kebabCase } from 'scule'
import type { ComponentsDir, Component } from '@nuxt/schema'
import { genDynamicImport } from 'mlly'
import { useNuxt } from './context'
import { ensureNuxtCompatibility } from './compatibility'

Expand Down Expand Up @@ -43,7 +44,7 @@ export function addComponent (opts: AddComponentOptions) {
shortPath: opts.filePath,
async: false,
level: 0,
asyncImport: `() => import(${JSON.stringify(opts.filePath)}).then(r => r['${opts.export || 'default'}'])`,
asyncImport: `${genDynamicImport(opts.filePath)}.then(r => r['${opts.export || 'default'}'])`,
import: `require(${JSON.stringify(opts.filePath)})['${opts.export || 'default'}']`,

...opts
Expand Down
5 changes: 3 additions & 2 deletions packages/kit/src/internal/template.ts
Expand Up @@ -3,6 +3,7 @@ import lodashTemplate from 'lodash.template'
import hash from 'hash-sum'
import { camelCase } from 'scule'
import { basename, extname } from 'pathe'
import { genDynamicImport, genImport } from 'mlly'

import type { NuxtTemplate } from '@nuxt/schema'

Expand Down Expand Up @@ -33,9 +34,9 @@ const importSources = (sources: string | string[], { lazy = false } = {}) => {
}
return sources.map((src) => {
if (lazy) {
return `const ${importName(src)} = () => import(${JSON.stringify(src)} /* webpackChunkName: ${JSON.stringify(src)} */)`
return `const ${importName(src)} = ${genDynamicImport(src, { comment: `webpackChunkName: ${JSON.stringify(src)}` })}`
}
return `import ${importName(src)} from ${JSON.stringify(src)}`
return genImport(src, importName(src))
}).join('\n')
}

Expand Down
3 changes: 2 additions & 1 deletion packages/nitro/src/build.ts
Expand Up @@ -2,6 +2,7 @@ import { relative, resolve, join } from 'pathe'
import consola from 'consola'
import * as rollup from 'rollup'
import fse from 'fs-extra'
import { genDynamicImport } from 'mlly'
import { printFSTree } from './utils/tree'
import { getRollupConfig } from './rollup/config'
import { hl, prettyPath, serializeTemplate, writeFile, isDirectory, readDirRecursively } from './utils'
Expand Down Expand Up @@ -76,7 +77,7 @@ async function writeTypes (nitroContext: NitroContext) {
if (typeof mw.handle !== 'string') { continue }
const relativePath = relative(nitroContext._nuxt.buildDir, mw.handle).replace(/\.[a-z]+$/, '')
routeTypes[mw.route] = routeTypes[mw.route] || []
routeTypes[mw.route].push(`Awaited<ReturnType<typeof import(${JSON.stringify(relativePath)}).default>>`)
routeTypes[mw.route].push(`Awaited<ReturnType<typeof ${genDynamicImport(relativePath, { wrapper: false })}.default>>`)
}

const lines = [
Expand Down
4 changes: 2 additions & 2 deletions packages/nitro/src/rollup/config.ts
Expand Up @@ -16,7 +16,7 @@ import { visualizer } from 'rollup-plugin-visualizer'
import * as unenv from 'unenv'

import type { Preset } from 'unenv'
import { sanitizeFilePath } from 'mlly'
import { sanitizeFilePath, genImport } from 'mlly'
import { NitroContext } from '../context'
import { resolvePath } from '../utils'
import { pkgDir } from '../dirs'
Expand Down Expand Up @@ -216,7 +216,7 @@ export const getRollupConfig = (nitroContext: NitroContext) => {

// Polyfill
rollupConfig.plugins.push(virtual({
'#polyfill': env.polyfill.map(p => `import '${p}';`).join('\n')
'#polyfill': env.polyfill.map(p => genImport(p)).join('\n')
}))

// https://github.com/rollup/plugins/tree/master/packages/alias
Expand Down
10 changes: 7 additions & 3 deletions packages/nitro/src/rollup/plugins/assets.ts
Expand Up @@ -4,6 +4,7 @@ import createEtag from 'etag'
import mime from 'mime'
import { resolve } from 'pathe'
import globby from 'globby'
import { genDynamicImport, genObjectFromRawEntries } from 'mlly'
import virtual from './virtual'

export interface AssetOptions {
Expand Down Expand Up @@ -81,9 +82,12 @@ function normalizeKey (key) {

function getAssetProd (assets: Record<string, Asset>) {
return `
const _assets = {\n${Object.entries(assets).map(([id, asset]) =>
` ['${normalizeKey(id)}']: {\n import: () => import(${JSON.stringify(asset.fsPath)}).then(r => r.default || r),\n meta: ${JSON.stringify(asset.meta)}\n }`
).join(',\n')}\n}
const _assets = ${genObjectFromRawEntries(
Object.entries(assets).map(([id, asset]) => [normalizeKey(id), {
import: genDynamicImport(asset.fsPath, { interopDefault: true }),
meta: asset.meta
}])
)}
${normalizeKey.toString()}
Expand Down
13 changes: 5 additions & 8 deletions packages/nitro/src/rollup/plugins/dynamic-require.ts
Expand Up @@ -2,6 +2,7 @@ import { pathToFileURL } from 'url'
import { resolve } from 'pathe'
import globby from 'globby'
import type { Plugin } from 'rollup'
import { genDynamicImport, genObjectFromRawEntries, genImport } from 'mlly'
import { serializeImportName } from '../../utils'

const PLUGIN_NAME = 'dynamic-require'
Expand Down Expand Up @@ -36,7 +37,7 @@ export function dynamicRequire ({ dir, ignore, inline }: Options): Plugin {
name: PLUGIN_NAME,
transform (code: string, _id: string) {
return {
code: code.replace(DYNAMIC_REQUIRE_RE, `import(${JSON.stringify(HELPER_DYNAMIC)}).then(r => r.default || r).then(dynamicRequire => dynamicRequire($1)).then`),
code: code.replace(DYNAMIC_REQUIRE_RE, `${genDynamicImport(HELPER_DYNAMIC, { wrapper: false, interopDefault: true })}.then(dynamicRequire => dynamicRequire($1)).then`),
map: null
}
},
Expand Down Expand Up @@ -89,10 +90,8 @@ async function getWebpackChunkMeta (src: string) {
}

function TMPL_INLINE ({ chunks }: TemplateContext) {
return `${chunks.map(i => `import * as ${i.name} from ${JSON.stringify(i.src)}`).join('\n')}
const dynamicChunks = {
${chunks.map(i => ` ['${i.id}']: ${i.name}`).join(',\n')}
};
return `${chunks.map(i => genImport(i.src, { name: '*', as: i.name }))}.join('\n')}
const dynamicChunks = ${genObjectFromRawEntries(chunks.map(i => [i.id, i.name]))};
export default function dynamicRequire(id) {
return Promise.resolve(dynamicChunks[id]);
Expand All @@ -101,9 +100,7 @@ export default function dynamicRequire(id) {

function TMPL_LAZY ({ chunks }: TemplateContext) {
return `
const dynamicChunks = {
${chunks.map(i => ` ['${i.id}']: () => import(${JSON.stringify(i.src)})`).join(',\n')}
};
const dynamicChunks = ${genObjectFromRawEntries(chunks.map(i => [i.id, genDynamicImport(i.src)]))};
export default function dynamicRequire(id) {
return dynamicChunks[id]();
Expand Down
16 changes: 10 additions & 6 deletions packages/nitro/src/rollup/plugins/middleware.ts
Expand Up @@ -3,6 +3,7 @@ import { relative } from 'pathe'
import table from 'table'
import isPrimitive from 'is-primitive'
import { isDebug } from 'std-env'
import { genArrayFromRaw, genDynamicImport, genImport } from 'mlly'
import type { ServerMiddleware } from '../../server/middleware'
import virtual from './virtual'

Expand Down Expand Up @@ -35,15 +36,18 @@ export function middleware (getMiddleware: () => ServerMiddleware[]) {
const lazyImports = unique(middleware.filter(m => m.lazy !== false && !imports.includes(m.handle)).map(m => m.handle))

return `
${imports.map(handle => `import ${getImportId(handle)} from ${JSON.stringify(handle)};`).join('\n')}
${imports.map(handle => `${genImport(handle, getImportId(handle))};`).join('\n')}
${lazyImports.map(handle => `const ${getImportId(handle)} = () => import(${JSON.stringify(handle)});`).join('\n')}
${lazyImports.map(handle => `const ${getImportId(handle)} = ${genDynamicImport(handle)};`).join('\n')}
const middleware = [
${middleware.map(m => `{ route: '${m.route}', handle: ${getImportId(m.handle)}, lazy: ${m.lazy || true}, promisify: ${m.promisify !== undefined ? m.promisify : true} }`).join(',\n')}
];
const middleware = ${genArrayFromRaw(middleware.map(m => ({
route: JSON.stringify(m.route),
handle: getImportId(m.handle),
lazy: m.lazy || true,
promisify: m.promisify !== undefined ? m.promisify : true
})))};
export default middleware
export default middleware
`
}
}
Expand Down
3 changes: 2 additions & 1 deletion packages/nitro/src/rollup/plugins/storage.ts
@@ -1,4 +1,5 @@
import virtual from '@rollup/plugin-virtual'
import { genImport } from 'mlly'
import { serializeImportName } from '../../utils'

export interface StorageOptions {
Expand Down Expand Up @@ -35,7 +36,7 @@ export function storage (opts: StorageOptions) {
import { createStorage } from 'unstorage'
import { assets } from '#assets'
${driverImports.map(i => `import ${serializeImportName(i)} from ${JSON.stringify(i)}`).join('\n')}
${driverImports.map(i => genImport(i, serializeImportName(i))).join('\n')}
export const storage = createStorage({})
Expand Down
3 changes: 2 additions & 1 deletion packages/nuxt3/src/auto-imports/module.ts
@@ -1,6 +1,7 @@
import { addVitePlugin, addWebpackPlugin, defineNuxtModule, addTemplate, resolveAlias, addPluginTemplate, useNuxt } from '@nuxt/kit'
import type { AutoImportsOptions } from '@nuxt/schema'
import { isAbsolute, join, relative, resolve, normalize } from 'pathe'
import { genDynamicImport } from 'mlly'
import { TransformPlugin } from './transform'
import { Nuxt3AutoImports } from './imports'
import { scanForComposables } from './composables'
Expand Down Expand Up @@ -126,7 +127,7 @@ function generateDts (ctx: AutoImportContext) {
write: true,
getContents: () => `// Generated by auto imports
declare global {
${ctx.autoImports.map(i => ` const ${i.as}: typeof import(${JSON.stringify(r(i.from))})['${i.name}']`).join('\n')}
${ctx.autoImports.map(i => ` const ${i.as}: typeof ${genDynamicImport(r(i.from), { wrapper: false })}['${i.name}']`).join('\n')}
}
export {}
Expand Down
5 changes: 3 additions & 2 deletions packages/nuxt3/src/auto-imports/utils.ts
@@ -1,4 +1,5 @@
import type { AutoImport } from '@nuxt/schema'
import { genExport, genImport } from 'mlly'

export function toImportModuleMap (autoImports: AutoImport[], isCJS = false) {
const aliasKeyword = isCJS ? ' : ' : ' as '
Expand All @@ -24,15 +25,15 @@ export function toImports (autoImports: AutoImport[], isCJS = false) {
.join('\n')
} else {
return Object.entries(map)
.map(([name, imports]) => `import { ${Array.from(imports).join(', ')} } from ${JSON.stringify(name)};`)
.map(([name, imports]) => genImport(name, Array.from(imports)))
.join('\n')
}
}

export function toExports (autoImports: AutoImport[]) {
const map = toImportModuleMap(autoImports, false)
return Object.entries(map)
.map(([name, imports]) => `export { ${Array.from(imports).join(', ')} } from '${name}';`)
.map(([name, imports]) => genExport(name, imports))
.join('\n')
}

Expand Down
3 changes: 2 additions & 1 deletion packages/nuxt3/src/components/loader.ts
@@ -1,6 +1,7 @@
import { createUnplugin } from 'unplugin'
import { parseQuery, parseURL } from 'ufo'
import { Component } from '@nuxt/schema'
import { genImport } from 'mlly'

interface LoaderOptions {
getComponents(): Component[]
Expand Down Expand Up @@ -36,7 +37,7 @@ function transform (content: string, components: Component[]) {
if (component) {
const identifier = map.get(component) || `__nuxt_component_${num++}`
map.set(component, identifier)
imports += `import ${identifier} from "${component.filePath}";`
imports += genImport(component.filePath, identifier)
return ` ${identifier}`
}
// no matched
Expand Down
13 changes: 6 additions & 7 deletions packages/nuxt3/src/components/templates.ts
@@ -1,6 +1,7 @@

import { relative } from 'pathe'
import type { Component } from '@nuxt/schema'
import { genDynamicImport, genObjectFromRawEntries } from 'mlly'

export type ComponentsTemplateOptions = {
buildDir?: string
Expand All @@ -27,14 +28,12 @@ export const componentsTemplate = {
getContents ({ options }: { options: ComponentsTemplateOptions }) {
return `import { defineAsyncComponent } from 'vue'
const components = {
${options.components.filter(c => c.global !== false).map((c) => {
const components = ${genObjectFromRawEntries(options.components.filter(c => c.global !== false).map((c) => {
const exp = c.export === 'default' ? 'c.default || c' : `c['${c.export}']`
const magicComments = createImportMagicComments(c)
const comment = createImportMagicComments(c)
return ` '${c.pascalName}': defineAsyncComponent(() => import(${JSON.stringify(c.filePath)} /* ${magicComments} */).then(c => ${exp}))`
}).join(',\n')}
}
return [c.pascalName, `defineAsyncComponent(${genDynamicImport(c.filePath, { comment })}.then(c => ${exp}))`]
}))}
export default function (nuxtApp) {
for (const name in components) {
Expand All @@ -52,7 +51,7 @@ export const componentsTypeTemplate = {
getContents: ({ options }: { options: ComponentsTemplateOptions }) => `// Generated by components discovery
declare module 'vue' {
export interface GlobalComponents {
${options.components.map(c => ` '${c.pascalName}': typeof import(${JSON.stringify(relative(options.buildDir, c.filePath))})['${c.export}']`).join(',\n')}
${options.components.map(c => ` '${c.pascalName}': typeof ${genDynamicImport(relative(options.buildDir, c.filePath), { wrapper: false })}['${c.export}']`).join(',\n')}
}
}
export {}
Expand Down
27 changes: 10 additions & 17 deletions packages/nuxt3/src/core/templates.ts
@@ -1,5 +1,6 @@
import { templateUtils } from '@nuxt/kit'
import type { Nuxt, NuxtApp } from '@nuxt/schema'
import { genArrayFromRaw, genDynamicImport, genExport, genImport } from 'mlly'

import { relative } from 'pathe'

Expand All @@ -11,23 +12,17 @@ type TemplateContext = {
// TODO: Use an alias
export const appComponentTemplate = {
filename: 'app-component.mjs',
getContents (ctx: TemplateContext) {
return `export { default } from ${JSON.stringify(ctx.app.mainComponent)}`
}
getContents: (ctx: TemplateContext) => genExport(ctx.app.mainComponent, ['default'])
}
// TODO: Use an alias
export const rootComponentTemplate = {
filename: 'root-component.mjs',
getContents (ctx: TemplateContext) {
return `export { default } from ${JSON.stringify(ctx.app.rootComponent)}`
}
getContents: (ctx: TemplateContext) => genExport(ctx.app.rootComponent, ['default'])
}

export const cssTemplate = {
filename: 'css.mjs',
getContents (ctx: TemplateContext) {
return ctx.nuxt.options.css.map(i => `import ${JSON.stringify(i.src || i)};`).join('\n')
}
getContents: (ctx: TemplateContext) => ctx.nuxt.options.css.map(i => genImport(i.src || i)).join('\n')
}

export const clientPluginTemplate = {
Expand All @@ -36,9 +31,7 @@ export const clientPluginTemplate = {
const clientPlugins = ctx.app.plugins.filter(p => !p.mode || p.mode !== 'server')
return [
templateUtils.importSources(clientPlugins.map(p => p.src)),
'export default [',
clientPlugins.map(p => templateUtils.importName(p.src)).join(',\n '),
']'
`export default ${genArrayFromRaw(clientPlugins.map(p => templateUtils.importName(p.src)))}`
].join('\n')
}
}
Expand All @@ -50,10 +43,10 @@ export const serverPluginTemplate = {
return [
"import preload from '#app/plugins/preload.server'",
templateUtils.importSources(serverPlugins.map(p => p.src)),
'export default [',
' preload,',
serverPlugins.map(p => templateUtils.importName(p.src)).join(',\n '),
']'
`export default ${genArrayFromRaw([
'preload',
...serverPlugins.map(p => templateUtils.importName(p.src))
])}`
].join('\n')
}
}
Expand Down Expand Up @@ -91,7 +84,7 @@ type Decorate<T extends Record<string, any>> = { [K in keyof T as K extends stri
type InjectionType<A extends Plugin> = A extends Plugin<infer T> ? Decorate<T> : unknown
type NuxtAppInjections = \n ${tsImports.map(p => `InjectionType<typeof import(${JSON.stringify(p)}).default>`).join(' &\n ')}
type NuxtAppInjections = \n ${tsImports.map(p => `InjectionType<typeof ${genDynamicImport(p, { wrapper: false })}.default>`).join(' &\n ')}
declare module '#app' {
interface NuxtApp extends NuxtAppInjections { }
Expand Down

0 comments on commit 49fd805

Please sign in to comment.