unplugin-vue-router: Vite hmr doesn't work with error: ReferenceError: Cannot access '_page_0' before initialization with unplugin-auto-import

When you modify template, the hmr doesn’t work with error: ReferenceError: Cannot access '_page_0' before initialization. you must press F5 to refresh the page.

<script setup>
const route = useRoute();
</script>
<template>
  <div>foo</div>
</template>

But if you manually import useRoute, this problem doesn’t exist

<script setup>
import { useRoute } from "vue-router";
const route = useRoute();
</script>
<template>
  <div>foo</div>
</template>

router.ts

import { createRouter, createWebHashHistory } from "vue-router";
import { routes } from "vue-router/auto/routes";

const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: [...routes],
});
export default router;

vite.config.ts

import { readFileSync } from "fs";
import { fileURLToPath, URL } from "node:url";
import { defineConfig } from "vite";
import VueRouter from "unplugin-vue-router/vite";
import {
  VueRouterAutoImports,
  getPascalCaseRouteName,
} from "unplugin-vue-router";
import vue from "@vitejs/plugin-vue";
import vueJsx from "@vitejs/plugin-vue-jsx";
import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import { AntDesignVueResolver } from "unplugin-vue-components/resolvers";
import VitePluginOss from "vite-plugin-oss";
import * as dotenv from "dotenv";
const dotenvExpand = require("dotenv-expand");

const { parsed: exposedEnvs } = dotenvExpand.expand({
  ...dotenv.config({
    override: false,
    path: ".env",
  }),
  ignoreProcessEnv: true,
});

const env = process.env;
for (const key of Object.keys(env).sort()) {
  // console.log(key, env[key]);
}
const VITE_PROXY_PREFIX = process.env.VITE_PROXY_PREFIX || "/toXodel";
const VITE_PROXY_PREFIX_REGEX = new RegExp("^" + VITE_PROXY_PREFIX);
const VITE_APP_NAME = process.env.VITE_APP_NAME;
const PROD_URL = `https:${env.ALIOSS_URL}${VITE_APP_NAME}/`;

const baseUrl = env.NODE_ENV == "production" ? PROD_URL : "/";

const plugins = [
  Components({
    dirs: ["./components"],
    extensions: ["vue"],
    dts: "./unplugin/components.d.ts",
    resolvers: [AntDesignVueResolver()],
  }),
  VueRouter({
    // Folder(s) to scan for vue components and generate routes. Can be a string, or
    // an object, or an array of those.
    routesFolder: ["src/views", "views"],

    // allowed extensions to be considered as routes
    extensions: [".vue"],

    // list of glob files to exclude from the routes generation
    // e.g. ['**/__*'] will exclude all files starting with `__`
    // e.g. ['**/__*/**/*'] will exclude all files within folders starting with `__`
    exclude: [],

    // Path for the generated types. Defaults to `./typed-router.d.ts` if typescript
    // is installed. Can be disabled by passing `false`.
    dts: "./unplugin/typed-router.d.ts",

    // Override the name generation of routes. unplugin-vue-router exports two versions:
    // `getFileBasedRouteName()` (the default) and `getPascalCaseRouteName()`. Import any
    // of them within your `vite.config.ts` file.
    getRouteName: getPascalCaseRouteName,

    // Customizes the default langage for `<route>` blocks
    // json5 is just a more permissive version of json
    routeBlockLang: "json5",

    // Change the import mode of page components. Can be 'async', 'sync', or a function with the following signature:
    // (filepath: string) => 'async' | 'sync'
    importMode: "sync",
  }),
  vue(),
  vueJsx({
    // https://github.com/vuejs/babel-plugin-jsx
    // https://github.com/vitejs/vite/tree/main/packages/plugin-vue-jsx
  }),
  AutoImport({
    //https://github.com/antfu/unplugin-auto-import#configuration
    eslintrc: {
      enabled: true, // Default `false`
      filepath: "./unplugin/.eslintrc-auto-import.json", // Default `./.eslintrc-auto-import.json`
      globalsPropValue: true, // Default `true`, (true | false | 'readonly' | 'readable' | 'writable' | 'writeable')
    },
    imports: [
      "vue",
      "pinia",
      // "vue-router", // comment this if using VueRouterAutoImports
      VueRouterAutoImports,
      { "vue-router/auto": ["useLink"] },
      "@vueuse/core",
      {
        // "@vueuse/core": [
        //   // named imports
        //   "useMouse", // import { useMouse } from '@vueuse/core',
        //   // "useFetch",
        //   // ["useFetch", "useMyFetch"], // import { useFetch as useMyFetch } from '@vueuse/core',
        // ],
        axios: [
          // default imports
          ["default", "axios"], // import { default as axios } from 'axios',
        ],
      },
    ],
    dts: "./unplugin/auto-imports.d.ts",
    vueTemplate: true,
    include: [
      /\.[tj]sx?$/, // .ts, .tsx, .js, .jsx
      /\.vue$/,
      /\.vue\?vue/, // .vue
    ],
    dirs: [
      "./components", // only root modules
      "./composables", // only root modules
      "./stores/**", // all nested modules
    ],
  }),
  {
    // this plugin handles ?b64 tags
    name: "vite-b64-plugin",
    transform(code, id) {
      if (!id.match(/\?b64$/)) return;
      // console.log(id, code);
      const path = id.replace(/\?b64/, "");
      const data = readFileSync(path, "base64");
      return `export default '${data}'`;
    },
  },
];
if (process.env.NODE_ENV == "production") {
  plugins.push(
    VitePluginOss({
      from: "./dist/**", // 上传那个文件或文件夹
      dist: `/${VITE_APP_NAME}`, // 需要上传到oss上的给定文件目录
      region: env.ALIOSS_REGION,
      accessKeyId: env.ALIOSS_KEY,
      accessKeySecret: env.ALIOSS_SECRET,
      bucket: env.ALIOSS_BUCKET,
      // test: true, // 测试,可以在进行测试看上传路径是否正确, 打开后只会显示上传路径并不会真正上传。默认false
      // 因为文件标识符 "\"  和 "/" 的区别 不进行 setOssPath配置,上传的文件夹就会拼到文件名上, 丢失了文件目录,所以需要对setOssPath 配置。
      setOssPath: (filePath) => {
        const index = filePath.lastIndexOf("dist");
        const Path = filePath.substring(index + 4, filePath.length);
        return Path.replace(/\\/g, "/");
      },
    })
  );
}
const proxyServer = `http://${env.NGINX_server_name}:${env.NGINX_listen}`;
export default defineConfig({
  base: baseUrl,
  define: {
    "process.env": exposedEnvs,
  },
  plugins,
  optimizeDeps: {
    include: ["vue"],
  },
  resolve: {
    alias: {
      "~/": fileURLToPath(new URL("./src", import.meta.url)) + "/",
    },
  },
  css: {
    preprocessorOptions: {
      less: {
        javascriptEnabled: true,
      },
    },
  },
  server: {
    // https://vitejs.dev/config/server-options.html#server-proxy
    // https://github.com/http-party/node-http-proxy#options
    port: Number(env.VITE_APP_PORT) || 5173,
    strictPort: true,
    proxy: {
      [VITE_PROXY_PREFIX]: {
        target: proxyServer,
        changeOrigin: true,
        rewrite: (path) => path.replace(VITE_PROXY_PREFIX_REGEX, ""),
      },
    },
  },
});

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Reactions: 2
  • Comments: 16 (7 by maintainers)

Commits related to this issue

Most upvoted comments

The more I think about this, the more I think routes shouldn’t be automatically added. Making the import of routes explicit would remove the circular dependency issue

Here is a little workaround that patches the routes array to be a function using a Vite-plugin. (Add to vite config plugins)

{
  // Hacky workaround until HMR in sync mode is fixed, see: https://github.com/posva/unplugin-vue-router/issues/132
  name: 'unplugin-vue-router-hmr-workaround',
  apply: 'serve',
  transform(code, id) {
    if (id === 'virtual:vue-router/auto') {
      return {
        code: code.replace('extendRoutes(routes) : routes', 'extendRoutes(routes()) : routes()')
      }
    }
    if (id === 'virtual:vue-router/auto-routes') {
      return {
        code: code.replace('export const routes = [', 'export const routes = () => [')
      }
    }
  }
}

This only runs on serve and makes HMR happy by using a function instead of defining the routes array directly in the module, which removes the cyclic dependency error in Vite.

Note that this will only work when using createRouter from vue-router/auto, and not if importing the routes directly from vue-router/auto-routes.

In the future, in my opinion, it would probably be best to remove the custom createRouter (and the import of vue-router/auto-routes) from vue-router/auto completely, and instead have the users import the routes manually when they set up the router. We don’t want vue-router/auto-routes to be imported on every page that uses things like useRouter() or useRoute() as this is what introduces the cyclic problem.

When using sync mode there seems to be (I think) a circular dependency somewhere creating the error you see when also using useRoute() with auto import (from vue-router/auto). Similar to issues reported at https://github.com/vitejs/vite/issues/3033

Using async (the default) doesn’t show this problem. Note that in your repro you are also importing the routes and calling vue-router createRouter() but you should do this instead (as shown in docs):

import { createRouter, createWebHashHistory } from 'vue-router/auto'

const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  extendRoutes(routes) {
    return routes
  }
})
export default router

Unfortunately, this doesn’t fix the problem. I recommend you to use async mode in the meantime or to toggle it for dev builds with importMode: process.env.NODE_ENV === 'production' ? 'sync' : 'async' or similar.

Contribution welcome!