vuejs / vue-hackernews-2.0

HackerNews clone built with Vue 2.0, vue-router & vuex, with server-side rendering
MIT License
10.96k stars 2.15k forks source link

window is not defined #327

Open melliott03 opened 6 years ago

melliott03 commented 6 years ago

How do I use plugins that require the browser's global window object?

I'm trying to use this package https://www.npmjs.com/package/vue2-google-maps

darkiron commented 6 years ago

test if window exist !

melliott03 commented 6 years ago

Thanks...I tried it in app.js and I get:

`Syntax Error: 'import' and 'export' may only appear at the top level (19:2)

17 | 18 | if(typeof window !== 'undefined'){ 19 | import * as VueGoogleMaps from 'vue2-google-maps' | ^ 20 |
21 | Vue.use(VueGoogleMaps, { 22 | load: {

@ ./src/entry-server.js 1:0-34

`

Here's my code

` import Vue from 'vue' import App from './App.vue' import { createStore } from './store' import { createRouter } from './router' import { sync } from 'vuex-router-sync' import titleMixin from './util/title' import * as filters from './util/filters'

import VueResource from 'vue-resource'

Vue.use(VueResource)

Vue.mixin(titleMixin) // mixin for handling title Object.keys(filters).forEach(key => { // register global utility filters. Vue.filter(key, filters[key]) })

if(typeof window !== 'undefined'){ import * as VueGoogleMaps from 'vue2-google-maps'

Vue.use(VueGoogleMaps, { load: { key: 'key' }, }) }

// json filter is now not bundled with vue Vue.filter('json', x => JSON.stringify(x));

// Expose a factory function that creates a fresh set of store, router, // app instances on each call (which is called for each SSR request) export function createApp () { // create store and router instances const store = createStore() const router = createRouter()

// sync the router with the vuex store. // this registers store.state.route sync(store, router)

// create the app instance. // here we inject the router, store and ssr context to all child components, // making them available everywhere as this.$router and this.$store. const app = new Vue({ router, store, render: h => h(App) })

// expose the app, the router and the store. // note we are not mounting the app here, since bootstrapping will be // different depending on whether we are in a browser or on the server. return { app, router, store } } `

darkiron commented 6 years ago

import first

and test

if(window) { Vue.use() }{

or create your component !

read the doc

anneincoding commented 5 years ago

I use jsdom, and it works , please checkout and try to put the code on your server.js

const { JSDOM } = require('jsdom');
const dom = new JSDOM('<!DOCTYPE html><html><body></body></html>', { 'url': 'http://localhost:9028' });

if (typeof window === 'undefined') {
  global.window = dom.window;
  global.document = window.document;
  global.navigator = window.navigator;
}