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

Error with classic Vue Router: ReferenceError: window is not defined #122

Closed
sdoerger opened this issue Oct 31, 2021 · 10 comments
Closed

Error with classic Vue Router: ReferenceError: window is not defined #122

sdoerger opened this issue Oct 31, 2021 · 10 comments

Comments

@sdoerger
Copy link

I am a big fan of vue-ssg and vitesse, but unfortunately I can not get vue-ssg running just with vue 3 and vue-router (and ts, tailwind, pinia in vite).

I saw other solutions here and tried them, but they did not work.
Probably they are wrong applied.
I. e.: #21 (comment) , if I try to import the router like that, I can not use it at all ...

Sorry if repeated, but with current solutions I am not able to make it work for my case ...

main.js

import { ViteSSG } from "vite-ssg";
import { createPinia } from "pinia";

import { routes } from "./router/index";

// if (typeof window !== "undefined") {
//   // import("./router/index");
//   const { routes } = await import('./router/index')
// }

// use any store you configured that you need data from on start-up
// import { useRootStore } from './store/root'
import { useTestStore } from "./store/modules/test.store";

import App from "./App.vue";

export const createApp = ViteSSG(
  App,
  { routes, base: "dist" },
  ({ app, router, initialState }) => {
    const pinia = createPinia();
    app.use(pinia);

    if (import.meta.env.SSR) {
      initialState.pinia = pinia.state.value;
    } else {
      pinia.state.value = initialState.pinia || {};
    }

    router.beforeEach((to, from, next) => {
      const store = useTestStore(pinia);
      // if (!store.ready)
      // perform the (user-implemented) store action to fill the store's state
      // store.initialize()
      next();
    });
  }
);

src/router/index.ts

import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
// import * as AUTHN from "../store/modules/authn.store";

export const routes: Array<RouteRecordRaw> = [
  {
    path: "",
    name: "Index",
    component: () =>
      import(
        /* webpackChunkName: 'Dashboard' */ "../views/Index/Index.vue"
      ),
    children: [
      {
        path: "dashboard",
        name: "Dashboard",
        component: () =>
          import(
            /* webpackChunkName: 'About' */ "../views/Index/Dashboard.vue"
          ),
        meta: {
          requireAuth: true,
        },
      },
      {
        path: "about",
        name: "About",
        component: () =>
          import(
            /* webpackChunkName: 'About' */ "../views/Index/About.vue"
          ),
        meta: {
          requireAuth: true,
        },
      },
    ],
  },
];

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  // history: createWebHistory(),
  routes,
});

export default router;

Complete error log

> vite-ssg build


[vite-ssg] Build for client...
vite v2.6.9 building for production...
✓ 42 modules transformed.
dist/assets/adminTool_icon.12695991.png   14.74 KiB
dist/index.html                           0.48 KiB
dist/ssr-manifest.json                    3.85 KiB
dist/assets/app.429ea4e5.js               2.42 KiB / gzip: 1.23 KiB
dist/assets/About.d269a00b.js             0.46 KiB / gzip: 0.33 KiB
dist/assets/Dashboard.2f3c36cd.js         0.36 KiB / gzip: 0.28 KiB
dist/assets/Index.55ff7a74.css            0.80 KiB / gzip: 0.28 KiB
dist/assets/Index.18795f9e.js             9.81 KiB / gzip: 4.60 KiB
dist/assets/vendor.3bc7b970.js            81.77 KiB / gzip: 32.25 KiB
dist/assets/app.84efe1fc.css              3196.14 KiB / gzip: 309.05 KiB

[vite-ssg] Build for server...
vite v2.6.9 building SSR bundle for production...
✓ 15 modules transformed.
.vite-ssg-temp/main.js                     22.72 KiB
.vite-ssg-temp/assets/style.1e869c80.css   3694.05 KiB
ReferenceError: window is not defined
    at useHistoryStateNavigation (/home/../test-vite-ssr/node_modules/vue-router/dist/vue-router.cjs.js:505:35)
    at Object.createWebHistory (/home/../test-vite-ssr/node_modules/vue-router/dist/vue-router.cjs.js:597:31)
    at Module.<anonymous> (/home/../test-vite-ssr/.vite-ssg-temp/main.js:41:22)
    at Module._compile (internal/modules/cjs/loader.js:1085:14)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
    at Module.load (internal/modules/cjs/loader.js:950:32)
    at Function.Module._load (internal/modules/cjs/loader.js:790:12)
    at Module.require (internal/modules/cjs/loader.js:974:19)
    at require (internal/modules/cjs/helpers.js:93:18)
    at build (/home/../test-vite-ssr/node_modules/vite-ssg/dist/node/cli.js:172:52)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! test-vite-ssr@0.0.0 generate: `vite-ssg build`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the test-vite-ssr@0.0.0 generate script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/.../.npm/_logs/2021-10-31T19_22_11_944Z-debug.log
The terminal process "zsh '-c', 'npm run generate'" terminated with exit code: 1.
@antfu antfu closed this as completed Nov 1, 2021
@sdoerger
Copy link
Author

sdoerger commented Nov 3, 2021

Thank you so much, for your god speed answer and fix.

But I do not know, what to do with the information.
I updated the repo and tried although to paste the lines in the index files (of where vite-ssg is located in my app).
But I seemed to like in your comment – kind off (history: client ? _vuerouter.createWebHistory.call...)

Still getting the same error. Could you please elaborate a bit, if you have time?
It would be so great, if I could just like that, errorless generate static sites in plain Vue3 and mean the world to me.

Thanks in advance

@ebisbe
Copy link

ebisbe commented Nov 8, 2021

@sdoerger did you fix it? I've just stumbled upon this error as well and can't understand @antfu answer :(

@sdoerger
Copy link
Author

sdoerger commented Nov 8, 2021

ebisbe unfortunately not.
So far I will use temporary use vitesse or vite-plugin-ssr's prerender option, which I have not tried yet.
Actually for the planned project I use Nuxt, which is generally awesome, but much overkill for my planned project.

But I hope, that if @antfu finds some time, maybe has an idea.

@userquin
Copy link
Member

userquin commented Nov 8, 2021

@ebisbe @sdoerger

The router is created by vite-ssg, in memory history or web client history, based on the target: the code will run on client but also on server when building: SSR + SSG.

You cannot create your onw router, you can only provide its configuration. To configure the router, you can provide the router options on your ViteSSG factory function call in your main.ts/main.js module: you can see where the router is created on Anthony's comment.

You can access the router on the ViteSSG callback (the context has router entry) and you need to use isClient to check if the callback is being called on client or in serve side: to check if SSR or SSG on server side, you can check process.env.SSR.

@userquin
Copy link
Member

userquin commented Nov 8, 2021

You cannot add logic referencing window when isClient is false since the server has not window defined, and so your error about window is undefined.

You can see this entry: #21 => #21 (comment)

@ebisbe
Copy link

ebisbe commented Nov 8, 2021

@sdoerger the error is not with this package but with Tailwind tailwindlabs/headlessui#840
They have relesed a new tag as for 7 hours ago with the fix. Prior to that they had it under '@next'
Btw, if you try it then check vueuse/head#34

@userquin Yeah. The issue is with another package not with this one. Everything is working for me now.

@sdoerger
Copy link
Author

sdoerger commented Nov 9, 2021

@userquin thank you much for the explanation. I check that and gotta keep that in mind.
@ebisbe wow, how did you find out that? Can not try it out now ... but does it mean it works now with the fix? Or what needs to be done?

Thanks

@ebisbe
Copy link

ebisbe commented Nov 9, 2021

@ebisbe I knew what Userquin said about not having 'window' on Node.js environment because I have experienced issues before with that. As the issue came from the tailwind package I assumed the error was from there so I just search in the issues repository.

what needs to be done?\

Upgrade "@headlessui/vue" to "^1.4.2" and it should not show that error. If you are using '@vueuse/head' with Node 14.x then you need to check vueuse/head#34 as you will encounter another issue. If you use a new Node version it should be working fine then

@FlickerMi
Copy link

const isServer = typeof window === 'undefined';
const history = isServer
  ? createMemoryHistory(import.meta.env.BASE_URL)
  : createWebHistory(import.meta.env.BASE_URL);

const routerOptions = {
  history: history,
  routes,
}

const router = createRouter(routerOptions);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants