Skip to content

Commit

Permalink
refactor: consistent route import for async and sync mode (hannoeru#187)
Browse files Browse the repository at this point in the history
  • Loading branch information
shkreios authored Mar 19, 2022
1 parent b443fb4 commit 39892da
Show file tree
Hide file tree
Showing 2 changed files with 97 additions and 35 deletions.
52 changes: 30 additions & 22 deletions src/stringify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,17 @@ function replaceFunction(_: any, value: any) {
return value
}

function getAsyncImportFunctionForResoler(resolver: string, path: string) {
switch (resolver) {
case 'react':
return `React.lazy(() => import('${path}'))`
case 'solid':
return `Solid.lazy(() => import('${path}'))`
default:
return `() => import('${path}')`
}
}

/**
* Creates a stringified Vue Router route definition.
*/
Expand All @@ -39,26 +50,23 @@ export function stringifyRoutes(

function componentReplacer(str: string, replaceStr: string, path: string) {
const mode = resolveImportMode(path, options)
if (mode === 'sync') {
const importName = pathToName(path)
const importStr = `import ${importName} from "${path}"`

// Only add import to array if it hasn't beed added before.
if (!imports.includes(importStr))
imports.push(importStr)

if (options.resolver === 'react')
return str.replace(replaceStr, `React.createElement(${importName})`)
else
return str.replace(replaceStr, importName)
} else {
if (options.resolver === 'react')
return str.replace(replaceStr, `React.createElement(React.lazy(() => import('${path}')))`)
else if (options.resolver === 'solid')
return str.replace(replaceStr, `Solid.lazy(() => import('${path}'))`)
else
return str.replace(replaceStr, `() => import('${path}')`)
}
const importName = pathToName(path)

const importStr = mode === 'sync'
? `import ${importName} from "${path}"`
: `const ${importName} = ${getAsyncImportFunctionForResoler(
options.resolver,
path,
)}`

// Only add import to array if it hasn't beed added before.
if (!imports.includes(importStr))
imports.push(importStr)

if (options.resolver === 'react')
return str.replace(replaceStr, `React.createElement(${importName})`)
else
return str.replace(replaceStr, importName)
}

function functionReplacer(str: string, replaceStr: string, content: string) {
Expand Down Expand Up @@ -86,9 +94,9 @@ export function generateClientCode(routes: any[], options: ResolvedOptions) {
const { imports, stringRoutes } = stringifyRoutes(routes, options)

if (options.resolver === 'react')
imports.push('import React from \"react\"')
imports.unshift('import React from "react"')
if (options.resolver === 'solid')
imports.push('import * as Solid from \"solid-js\"')
imports.unshift('import * as Solid from "solid-js"')

return `${imports.join(';\n')};\n\nconst routes = ${stringRoutes};\n\nexport default routes;`
}
Loading

0 comments on commit 39892da

Please sign in to comment.