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

Angular 4 + Universal: Window is not defined #134

Closed
mchambaud opened this issue Jun 22, 2017 · 28 comments
Closed

Angular 4 + Universal: Window is not defined #134

mchambaud opened this issue Jun 22, 2017 · 28 comments

Comments

@mchambaud
Copy link

mchambaud commented Jun 22, 2017

Everything works fine using ng serve and it compiles fine with ngc but I get the following exception at runtime.

ReferenceError: window is not defined
    at Ng2LocationServices.BaseLocationServices (/Users/Michael/Documents/my-app/node_modules/@uirouter/core/lib/vanilla/baseLocationService.js:20:26)
    at new Ng2LocationServices (/Users/Michael/Documents/my-app/dist/out-tsc/src/server.js:3923:28)
    at uiRouterFactory (/Users/Michael/Documents/my-app/dist/out-tsc/src/server.js:2656:30)
    at _callFactory (/Users/Michael/Documents/my-app/node_modules/@angular/core/bundles/core.umd.js:9650:34)
    at _createProviderInstance$1 (/Users/Michael/Documents/my-app/node_modules/@angular/core/bundles/core.umd.js:9579:26)
    at initNgModule (/Users/Michael/Documents/my-app/node_modules/@angular/core/bundles/core.umd.js:9530:13)
    at new NgModuleRef_ (/Users/Michael/Documents/my-app/node_modules/@angular/core/bundles/core.umd.js:10638:9)
    at Object.createNgModuleRef (/Users/Michael/Documents/my-app/node_modules/@angular/core/bundles/core.umd.js:10622:12)
    at NgModuleFactory_.create (/Users/Michael/Documents/my-app/node_modules/@angular/core/bundles/core.umd.js:13901:25)
    at /Users/Michael/Documents/my-app/node_modules/@angular/core/bundles/core.umd.js:4588:61
    at ZoneDelegate.invoke (/Users/Michael/Documents/my-app/node_modules/zone.js/dist/zone-node.js:365:26)
    at Object.onInvoke (/Users/Michael/Documents/my-app/node_modules/@angular/core/bundles/core.umd.js:3965:37)
    at ZoneDelegate.invoke (/Users/Michael/Documents/my-app/node_modules/zone.js/dist/zone-node.js:364:32)
    at Zone.run (/Users/Michael/Documents/my-app/node_modules/zone.js/dist/zone-node.js:125:43)
    at NgZone.run (/Users/Michael/Documents/my-app/node_modules/@angular/core/bundles/core.umd.js:3833:62)

this is my app.server.module.ts

import { NgModule } from '@angular/core';
import { ServerModule } from '@angular/platform-server';
import { BrowserModule } from '@angular/platform-browser';
import { AppModule } from './app.module';
import { AppComponent } from './app.component';
import { LocationStrategy } from '@angular/common';
import { UIRouter, MemoryLocationConfig, MemoryLocationService } from '@uirouter/angular';

@NgModule({
    imports: [
        BrowserModule.withServerTransition({ appId: 'my-app' }),
        ServerModule,
        AppModule
    ],
    bootstrap: [AppComponent]
})

export class AppServerModule {
    constructor(router: UIRouter, locationStrategy: LocationStrategy) {
        router.locationConfig = new MemoryLocationConfig();
        router.locationService = new MemoryLocationService(router);
        router.locationService['_url'] = locationStrategy.path(true);
    }
}

Did what #43 said to do but no luck.

@aitboudad
Copy link
Contributor

Universal support is in progress (just a few little tweaks remain)
if you use webpack you can make it work by overriding window & location variable.

@mchambaud
Copy link
Author

mchambaud commented Jun 23, 2017

What would be the best way to achieve this? Do you have an example laying around?

@aitboudad
Copy link
Contributor

Right now I'm using DefinePlugin:

new DefinePlugin({
    window: undefined,
    document: undefined,
    location: JSON.stringify({
        protocol: 'https', // `http` or `https`
        host: `your host`,
    })
}),

@mchambaud
Copy link
Author

mchambaud commented Jun 23, 2017

So I'm using angular-cli and I have a webpack.config for some server stuff which is where I've put this but it does not seem to work...

const path = require('path');
const nodeExternals = require('webpack-node-externals');
const webpack = require('webpack');

module.exports = {
    entry: {
        server: './src/server.ts'
    },
    resolve: {
        extensions: ['.ts', '.js']
    },
    target: 'node',
    externals: [nodeExternals({
        whitelist: [
            /^@ngx-translate\/core/,
            /^@uirouter\/angular/
        ]
    })],
    node: {
        __dirname: true
    },
    output: {
        path: path.join(__dirname, 'dist/out-tsc/src'),
        filename: '[name].js'
    },
    module: {
        rules: [
            { test: /\.ts$/, loader: 'ts-loader' }
        ]
    },
    plugins: [
        new webpack.DefinePlugin({
            window: undefined,
            document: undefined,
            location: JSON.stringify({
                protocol: 'https',
                host: `localhost`,
            })
        })
    ]
};

@aitboudad
Copy link
Contributor

@mchambaud which version of uirouter do you use ?

@mchambaud
Copy link
Author

1.0.0-beta.7

@aitboudad
Copy link
Contributor

you should remove @uirouter/angular in externals entry

@mchambaud
Copy link
Author

mchambaud commented Jun 23, 2017

ngc exploses without it

/Users/Michael/Documents/my-app/node_modules/@uirouter/angular/lib/directives/uiView.js:3
import { Component, ComponentFactoryResolver, ViewContainerRef, Input, ReflectiveInjector, ViewChild, Inject } from '@angular/core';
^^^^^^
SyntaxError: Unexpected token import
    at createScript (vm.js:56:10)
    at Object.runInThisContext (vm.js:97:10)
    at Module._compile (module.js:542:28)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/Users/Michael/Documents/my-app/dist/out-tsc/src/server.js:2104:18)
    at __webpack_require__ (/Users/Michael/Documents/my-app/dist/out-tsc/src/server.js:20:30)
    at Object.defineProperty.value (/Users/Michael/Documents/my-app/dist/out-tsc/src/server.js:1815:10)
    at __webpack_require__ (/Users/Michael/Documents/my-app/dist/out-tsc/src/server.js:20:30)
    at Object.<anonymous> (/Users/Michael/Documents/my-app/dist/out-tsc/src/server.js:2128:10)
    at __webpack_require__ (/Users/Michael/Documents/my-app/dist/out-tsc/src/server.js:20:30)

@aitboudad
Copy link
Contributor

can you use my repo to check if it's work in your project

"@uirouter/angular": "https://github.com/aitboudad/ng2#f8201c2c368baa759b32e392a1308fc26e09a176",

instead of:

import {} from @uirouter/angular

use:

import {} from @uirouter/angular/src

@mchambaud
Copy link
Author

mchambaud commented Jun 23, 2017

Ok wil do that right away

@mchambaud
Copy link
Author

mchambaud commented Jun 23, 2017

I get error with the imports to @uirouter/angular/src can't resolve

I changed all occurrences to something like this

import { UIRouterModule } from '@uirouter/angular/src';

Seems like there's no src folder in my node_modules/@uirouter/angular

screen shot 2017-06-23 at 12 13 18 pm

@aitboudad
Copy link
Contributor

you should target the folder node_modules/@uirouter/angular/src which contains the ts files (check if exist firstly).
I think we don't use the same tools, I'll try to provide you a working example in a separate repo in weekend.

@mchambaud
Copy link
Author

mchambaud commented Jun 23, 2017

When I npm install your package there is no src folder :\

are you on gitter by any chance?

@aitboudad
Copy link
Contributor

can you update package hash and try again

"@uirouter/angular": "https://github.com/aitboudad/ng2#a7e3387a7a821c105ce6e8538657d4cd161ed881",

@mchambaud
Copy link
Author

mchambaud commented Jun 23, 2017

So! It compiles!

But I get window is not defined at runtime..

Do you want to Screenhero or Skype real quick see if it's a stupid mistake on my part?

@mchambaud
Copy link
Author

My skype is the same as my GitHub username

@mchambaud
Copy link
Author

Maybe I can help finish @uirouter for Universal. What pending tasks is there?

@aitboudad
Copy link
Contributor

@aitboudad
Copy link
Contributor

@Superd22
Copy link

Superd22 commented Aug 5, 2017

@aitboudad shouldn't this be a ui-router/core issue then ?
There's nothing you can do from Ng2LocationServices.

@christopherthielen
Copy link
Member

Note the base location services class has been updated: ui-router/core@a4629ee#diff-aee9f1b1f04ef087e5d4b8ff17e636fc

@atmman
Copy link

atmman commented Sep 27, 2017

@christopherthielen - Could you please tell me when this fix will be released?

@atmman
Copy link

atmman commented Oct 16, 2017

@aitboudad @christopherthielen I tries to enable server side rendering for my project. But it looks like it's impossible to use @uirouter/angular lib with node.js. I've prepared project using angular-cli guide for server side rendering (https://github.com/angular/angular-cli/wiki/stories-universal-rendering) and tries to build backend code. Build process finishes fine but I got an error when I run backend app:

/home/atm/projects/proj/proj/backend/node_modules/@uirouter/angular/lib/directives/uiView.js:3 import { Component, ComponentFactoryResolver, ViewContainerRef, Input, ReflectiveInjector, ViewChild, Inject } from '@angular/core'; ^^^^^^ SyntaxError: Unexpected token import at Object.exports.runInThisContext (vm.js:76:16) at Module._compile (module.js:542:28) at Object.Module._extensions..js (module.js:579:10) at Module.load (module.js:487:32) at tryModuleLoad (module.js:446:12) at Function.Module._load (module.js:438:3) at Module.require (module.js:497:17) at require (internal/module.js:20:19) at Object./BYt (/home/atm/projects/proj/proj/backend/output/client/server/main.bundle.js:1:61842)

I use beta-8 version. Could you please tell me is there a way to use ui-router on the backend for now?

@atmman
Copy link

atmman commented Oct 16, 2017

Here is my webpack.config.js:

const path = require('path');
const webpack = require('webpack');
const nodeExternals = require('webpack-node-externals');

module.exports = {
  entry: {  server: './app.ts' },
  resolve: { extensions: ['.ts', '.js'] },
  resolveLoader: {
    modules: [
      './node_modules',
      './node_modules'
    ]
  },
  target: 'node',
  externals: [
    nodeExternals({})
  ],
  output: {
    path: path.join(__dirname, 'dist'),
    filename: '[name].js',
    libraryTarget: 'commonjs'
  },
  module: {
    rules: [
      { test: /\.ts$/, loader: 'ts-loader' },
      { test: /\.json$/, loader: "raw-loader"},
    ]
  },
  plugins: [
    // Temporary Fix for issue: https://github.com/angular/angular/issues/11580
    // for "WARNING Critical dependency: the request of a dependency is an expression"
    new webpack.ContextReplacementPlugin(
      /(.+)?angular(\\|\/)core(.+)?/,
      path.join(__dirname, 'src'), // location of your src
      {} // a map of your routes
    ),
    new webpack.ContextReplacementPlugin(
      /(.+)?express(\\|\/)(.+)?/,
      path.join(__dirname, 'src')
    )
  ]
};

@christopherthielen
Copy link
Member

christopherthielen commented Oct 21, 2017

@atmman

I followed the instructions at https://github.com/angular/angular-cli/wiki/stories-universal-rendering and was able to get the UI-Router Sample App working as a universal app.

I published it as a branch named angular-universal

Here is the relevant commit: ui-router/sample-app-angular@b642962

To try it out, fetch the repository, switch to angular-universal branch, run yarn, then npm run build:dynamic && npm run serve:dynamic

@christopherthielen
Copy link
Member

christopherthielen commented Oct 21, 2017

To debug the server-side app, you might want to try node --inspect-brk dist/server.js using node 8.x or higher

@atmman9001
Copy link

@christopherthielen Thank you. I've solved my problem. It was related to libs in my backend app. I've excluded it from the result backend bundle with nodeModules webpack extension.

@christopherthielen
Copy link
Member

I think this was fixed in some previous release. Please let me know if it is not.

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

6 participants