mmenu-js icon indicating copy to clipboard operation
mmenu-js copied to clipboard

Webpack window is not defined error - Nuxt App

Open jgmdigital opened this issue 3 years ago • 1 comments

Hi there, has anyone managed to get this working with a Nuxt application?

We have installed via NPM, created a test component with the following markup:

<template>
    <nav id="menu">
        <ul>
            <li><a href="/">Home</a></li>
            <li>
                <a href="/about/">About us</a>
                <ul>
                    <li><a href="/about/history/">History</a></li>
                    <li><a href="/about/team/">The team</a></li>
                    <li><a href="/about/address/">Our address</a></li>
                </ul>
            </li>
            <li><a href="/contact/">Contact</a></li>
        </ul>
    </nav>
</template>
<script>
import Mmenu from 'mmenu-js'

export default {
    mounted() {
        const menuSelector = '#menu'
        const menu = new Mmenu(document.querySelector(menuSelector))
    },
}
</script>

However, the console throws the following error:

client.js?06a0:57 [Vue warn]: Failed to resolve async component: () => __webpack_require__.e(/*! import() | components/menu-mobile-nav */ "components/menu-mobile-nav").then(__webpack_require__.bind(null, /*! ../../components/molecules/MenuMobileNav.vue */ "./components/molecules/MenuMobileNav.vue")).then(c => Object(_utils__WEBPACK_IMPORTED_MODULE_1__["wrapFunctional"])(c.default || c))
Reason: ReferenceError: window is not defined

Any help would be greatly appreciated.

jgmdigital avatar Jul 20 '22 11:07 jgmdigital

Different parts of the plugin use the window object for binding event listeners, matchmedia, session storage and scrolling. Some could probably use the document instead of the window, but I don't think all can. The most proposed solution appears to be testing whether the window excists, something like this:

if (typeof window !== 'undefined') {
    const menuSelector = '#menu'
    const menu = new Mmenu(document.querySelector(menuSelector))
}

Hope this helps.

FrDH avatar Jul 26 '22 19:07 FrDH