Skip to content

build code transform error using react router createBrowserRouter syntax with lazy import #17655

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

Closed
7 tasks done
Em-Ant opened this issue Jul 11, 2024 · 2 comments · Fixed by #17687
Closed
7 tasks done
Labels
p4-important Violate documented behavior or significantly improves performance (priority) regression The issue only appears after a new release

Comments

@Em-Ant
Copy link

Em-Ant commented Jul 11, 2024

Describe the bug

the code

const router = createBrowserRouter([
  {
    path: "/",
    element: <Layout />,
    children: [
      { index: true, element: <Navigate to="/counter" replace /> },
      {
        path: "counter",
        async lazy() {
          const { CounterPage } = await import("./pages");
          return { element: <CounterPage /> };
        },
      },
    ],
  },
  

in vite >= 5.3.1 is transformed by build-import-analysis plugin into:

const router = createBrowserRouter([
{
  path: "/",
  element: /* @__PURE__ */ jsx(Layout, {}),
  children: [
    { index: true, element: /* @__PURE__ */ jsx(Navigate, { to: "/counter", replace: true }) },
    {
      path: "counter",
      async lazy() {
        const { CounterPage } = await __vitePreload(async () => { const {
      path: "counter",
      async lazy() {
        const { CounterPage } = await import("./pages");return {
      path: "counter",
      async lazy() {
        const { CounterPage }},__VITE_IS_MODERN__?__VITE_PRELOAD__:void 0);
        return { element: /* @__PURE__ */ jsx(CounterPage, {}) };
      }
    }
  ]
}
]);

instead of:

const router = createBrowserRouter([
  {
    path: "/",
    element: /* @__PURE__ */ jsx(Layout, {}),
    children: [
      { index: true, element: /* @__PURE__ */ jsx(Navigate, { to: "/counter", replace: true }) },
      {
        path: "counter",
        async lazy() {
          const { CounterPage } = await __vitePreload(async () => { const { CounterPage } = await import("./pages");return { CounterPage }},__VITE_IS_MODERN__?__VITE_PRELOAD__:void 0);
          return { element: /* @__PURE__ */ jsx(CounterPage, {}) };
        }
      }
    ]
  }
]);

in vite <= 5.3.0.

The bug has been introduced in version 5.3.1 and it's likely caused by this commit

(inspected with vite-plugin-inspect)

Reproduction

https://codesandbox.io/p/devbox/async-import-issue-2yyznw?file=%2Fpackage.json%3A15%2C34

Steps to reproduce

  • download the sandbox
  • run pnpm build

you will get the error

src/router.tsx (19:17): Unexpected token `string literal (counter, "counter")`. Expected yield, an identifier, [ or { (Note that you need plugins to import files that are not JavaScript)
file: /home/emanuele/Scrivania/sandbox/src/router.tsx:19:17

17:         async lazy() {
18:           const { CounterPage } = await import("./pages");
19:           return { element: <CounterPage /> };
                     ^
20:         },
21:       },

if you run pnpm dev everything is ok.

System Info

Ubuntu 22.04, node 20.12.2, Firefox 127.0.2

Used Package Manager

pnpm

Logs

> tsc && vite build "--debug"

  vite:config bundled config file loaded in 16.08ms +0ms
  vite:config using resolved config: {
  vite:config   plugins: [
  vite:config     'vite:build-metadata',
  vite:config     'vite:watch-package-data',
  vite:config     'vite:pre-alias',
  vite:config     'alias',
  vite:config     'vite:react-babel',
  vite:config     'vite:react-refresh',
  vite:config     'vite:modulepreload-polyfill',
  vite:config     'vite:resolve',
  vite:config     'vite:html-inline-proxy',
  vite:config     'vite:css',
  vite:config     'vite:esbuild',
  vite:config     'vite:json',
  vite:config     'vite:wasm-helper',
  vite:config     'vite:worker',
  vite:config     'vite:asset',
  vite:config     'vite:wasm-fallback',
  vite:config     'vite:define',
  vite:config     'vite:css-post',
  vite:config     'vite:build-html',
  vite:config     'vite:worker-import-meta-url',
  vite:config     'vite:asset-import-meta-url',
  vite:config     'vite:force-systemjs-wrap-complete',
  vite:config     'commonjs',
  vite:config     'vite:data-uri',
  vite:config     'vite:dynamic-import-vars',
  vite:config     'vite:import-glob',
  vite:config     'vite:build-import-analysis',
  vite:config     'vite:esbuild-transpile',
  vite:config     'vite:terser',
  vite:config     'vite:reporter',
  vite:config     'vite:load-fallback'
  vite:config   ],
  vite:config   build: {
  vite:config     target: [ 'es2020', 'edge88', 'firefox78', 'chrome87', 'safari14' ],
  vite:config     cssTarget: [ 'es2020', 'edge88', 'firefox78', 'chrome87', 'safari14' ],
  vite:config     outDir: 'dist',
  vite:config     assetsDir: 'assets',
  vite:config     assetsInlineLimit: 4096,
  vite:config     cssCodeSplit: true,
  vite:config     sourcemap: false,
  vite:config     rollupOptions: { onwarn: [Function: onwarn] },
  vite:config     minify: 'esbuild',
  vite:config     terserOptions: {},
  vite:config     write: true,
  vite:config     emptyOutDir: null,
  vite:config     copyPublicDir: true,
  vite:config     manifest: false,
  vite:config     lib: false,
  vite:config     ssr: false,
  vite:config     ssrManifest: false,
  vite:config     ssrEmitAssets: false,
  vite:config     reportCompressedSize: true,
  vite:config     chunkSizeWarningLimit: 500,
  vite:config     watch: null,
  vite:config     commonjsOptions: { include: [Array], extensions: [Array] },
  vite:config     dynamicImportVarsOptions: { warnOnError: true, exclude: [Array] },
  vite:config     modulePreload: { polyfill: true },
  vite:config     cssMinify: true
  vite:config   },
  vite:config   esbuild: { jsxDev: false, jsx: 'automatic', jsxImportSource: undefined },
  vite:config   optimizeDeps: {
  vite:config     holdUntilCrawlEnd: true,
  vite:config     esbuildOptions: { preserveSymlinks: false, jsx: 'automatic' },
  vite:config     include: [ 'react', 'react/jsx-dev-runtime', 'react/jsx-runtime' ]
  vite:config   },
  vite:config   resolve: {
  vite:config     mainFields: [ 'browser', 'module', 'jsnext:main', 'jsnext' ],
  vite:config     conditions: [],
  vite:config     extensions: [
  vite:config       '.mjs',  '.js',
  vite:config       '.mts',  '.ts',
  vite:config       '.jsx',  '.tsx',
  vite:config       '.json'
  vite:config     ],
  vite:config     dedupe: [ 'react', 'react-dom' ],
  vite:config     preserveSymlinks: false,
  vite:config     alias: [ [Object], [Object] ]
  vite:config   },
  vite:config   configFile: '/home/emanuele/Scrivania/sandbox/vite.config.ts',
  vite:config   configFileDependencies: [ '/home/emanuele/Scrivania/sandbox/vite.config.ts' ],
  vite:config   inlineConfig: {
  vite:config     root: undefined,
  vite:config     base: undefined,
  vite:config     mode: undefined,
  vite:config     configFile: undefined,
  vite:config     logLevel: undefined,
  vite:config     clearScreen: undefined,
  vite:config     build: {}
  vite:config   },
  vite:config   root: '/home/emanuele/Scrivania/sandbox',
  vite:config   base: '/',
  vite:config   rawBase: '/',
  vite:config   publicDir: '/home/emanuele/Scrivania/sandbox/public',
  vite:config   cacheDir: '/home/emanuele/Scrivania/sandbox/node_modules/.vite',
  vite:config   command: 'build',
  vite:config   mode: 'production',
  vite:config   ssr: {
  vite:config     target: 'node',
  vite:config     optimizeDeps: { noDiscovery: true, esbuildOptions: [Object] }
  vite:config   },
  vite:config   isWorker: false,
  vite:config   mainConfig: null,
  vite:config   bundleChain: [],
  vite:config   isProduction: true,
  vite:config   css: { lightningcss: undefined },
  vite:config   server: {
  vite:config     preTransformRequests: true,
  vite:config     sourcemapIgnoreList: [Function: isInNodeModules$1],
  vite:config     middlewareMode: false,
  vite:config     fs: {
  vite:config       strict: true,
  vite:config       allow: [Array],
  vite:config       deny: [Array],
  vite:config       cachedChecks: undefined
  vite:config     }
  vite:config   },
  vite:config   preview: {
  vite:config     port: undefined,
  vite:config     strictPort: undefined,
  vite:config     host: undefined,
  vite:config     https: undefined,
  vite:config     open: undefined,
  vite:config     proxy: undefined,
  vite:config     cors: undefined,
  vite:config     headers: undefined
  vite:config   },
  vite:config   envDir: '/home/emanuele/Scrivania/sandbox',
  vite:config   env: { BASE_URL: '/', MODE: 'production', DEV: false, PROD: true },
  vite:config   assetsInclude: [Function: assetsInclude],
  vite:config   logger: {
  vite:config     hasWarned: false,
  vite:config     info: [Function: info],
  vite:config     warn: [Function: warn],
  vite:config     warnOnce: [Function: warnOnce],
  vite:config     error: [Function: error],
  vite:config     clearScreen: [Function: clearScreen],
  vite:config     hasErrorLogged: [Function: hasErrorLogged]
  vite:config   },
  vite:config   packageCache: Map(1) {
  vite:config     'fnpd_/home/emanuele/Scrivania/sandbox' => {
  vite:config       dir: '/home/emanuele/Scrivania/sandbox',
  vite:config       data: [Object],
  vite:config       hasSideEffects: [Function: hasSideEffects],
  vite:config       webResolvedImports: {},
  vite:config       nodeResolvedImports: {},
  vite:config       setResolvedCache: [Function: setResolvedCache],
  vite:config       getResolvedCache: [Function: getResolvedCache]
  vite:config     },
  vite:config     set: [Function (anonymous)]
  vite:config   },
  vite:config   createResolver: [Function: createResolver],
  vite:config   worker: { format: 'iife', plugins: '() => plugins', rollupOptions: {} },
  vite:config   appType: 'spa',
  vite:config   experimental: { importGlobRestoreExtension: false, hmrPartialAccept: false },
  vite:config   getSortedPlugins: [Function: getSortedPlugins],
  vite:config   getSortedPluginHooks: [Function: getSortedPluginHooks]
  vite:config } +14ms
vite v5.3.3 building for production...
✓ 14 modules transformed.
x Build failed in 77ms
error during build:
src/router.tsx (19:17): Unexpected token "string literal (counter, "counter")". Expected yield, an identifier, [ or { (Note that you need plugins to import files that are not JavaScript)
file: /home/emanuele/Scrivania/sandbox/src/router.tsx:19:17

17:         async lazy() {
18:           const { CounterPage } = await import("./pages");
19:           return { element: <CounterPage /> };
                     ^
20:         },
21:       },

RollupError: Unexpected token "string literal (counter, "counter")". Expected yield, an identifier, [ or {
    at getRollupError (file:///home/emanuele/Scrivania/sandbox/node_modules/.pnpm/[email protected]/node_modules/rollup/dist/es/shared/parseAst.js:376:41)
    at ParseError.initialise (file:///home/emanuele/Scrivania/sandbox/node_modules/.pnpm/[email protected]/node_modules/rollup/dist/es/shared/node-entry.js:11158:28)
    at convertNode (file:///home/emanuele/Scrivania/sandbox/node_modules/.pnpm/[email protected]/node_modules/rollup/dist/es/shared/node-entry.js:12898:10)
    at convertProgram (file:///home/emanuele/Scrivania/sandbox/node_modules/.pnpm/[email protected]/node_modules/rollup/dist/es/shared/node-entry.js:12218:12)
    at Module.setSource (file:///home/emanuele/Scrivania/sandbox/node_modules/.pnpm/[email protected]/node_modules/rollup/dist/es/shared/node-entry.js:14042:24)
    at async ModuleLoader.addModuleSource (file:///home/emanuele/Scrivania/sandbox/node_modules/.pnpm/[email protected]/node_modules/rollup/dist/es/shared/node-entry.js:18681:13)
 ELIFECYCLE  Command failed with exit code 1.
 

Validations

@stevan-borus
Copy link

stevan-borus commented Jul 12, 2024

Same situation. I have a bit of a different error:

Expected ',', got 'lazy' (Note that you need plugins to import files that are not JavaScript)

139:           },
140:           {
141:             path: 'terms-of-use',
                       ^
142:             async lazy() {
143:               const { TermsOfUse } = await import('@/pages/terms-of-use/TermsOfUse');

RollupError: Expected ',', got 'lazy'

@TimVerheul
Copy link

Same issue here. Also at the router file

Unexpected token `string literal (deploy, "deploy")`. Expected yield, an identifier, [ or { (Note that you need plugins to import files that are not JavaScript)

33:             async lazy() {
34:               const { Auth } = await __vitePreload(async () => { const { 
35:         path: "deploy",
                  ^
36:         children: [
37:           {

RollupError: Unexpected token `string literal (deploy, "deploy")`. Expected yield, an identifier, [ or {
    at getRollupError

@bluwy bluwy added p4-important Violate documented behavior or significantly improves performance (priority) regression The issue only appears after a new release and removed pending triage labels Jul 15, 2024
@github-actions github-actions bot locked and limited conversation to collaborators Jul 30, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
p4-important Violate documented behavior or significantly improves performance (priority) regression The issue only appears after a new release
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants