Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

utility function to resolve React.lazy imports #3

Open
scarf005 opened this issue Feb 14, 2024 · 0 comments
Open

utility function to resolve React.lazy imports #3

scarf005 opened this issue Feb 14, 2024 · 0 comments
Assignees
Labels
feat New feature or request

Comments

@scarf005
Copy link
Contributor

scarf005 commented Feb 14, 2024

Example implementation

const resolveDynamicImportPath = (path: string) =>
  resolve(import.meta.dirname!) + path.replace('@src', '/src') + '.tsx'

const projectCache = new Project({
  useInMemoryFileSystem: true,
})

export const getRouteMappings =
  (resolveDynamicImport: (path: string) => string) =>
  (sourceFile: SourceFile): Record<string, string> => {
    const nodes = query(
      sourceFile.getText(),
      'Identifier[name=routes] ~ ObjectLiteralExpression > PropertyAssignment'
    ).flatMap((x) => {
      const container = query(x, 'Identifier[name=component] ~ Identifier')[0]
      if (container === undefined) return []

      const topDecl = sourceFile.getVariableDeclarationOrThrow(container?.getText())

      // HACK: assumes all components are of format React.lazy(() => import('<path>/componentName'))
      const path = topDecl.getFirstDescendantByKindOrThrow(SyntaxKind.StringLiteral)
      const resolvedPath = resolveDynamicImport(path.getLiteralText())
      const resolvedText = Deno.readTextFileSync(resolvedPath)

      const srcfile = projectCache.createSourceFile(resolvedPath, resolvedText)
      // https://ts-morph.com/details/exports#getting-exported-declarations
      const uri = encodeVSCodeURI(srcfile.getExportedDeclarations().get('default')![0])
      projectCache.removeSourceFile(srcfile)

      const name = query(x, 'PropertyAccessExpression Identifier[name=Route] ~ Identifier')[0]?.getText()

      return [[name, uri]] as const
    })

    return Object.fromEntries(nodes)
  }
@scarf005 scarf005 self-assigned this Feb 14, 2024
@scarf005 scarf005 added the feat New feature or request label Feb 14, 2024
@scarf005 scarf005 assigned scarf005 and unassigned scarf005 Feb 21, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feat New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant