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

Problem loading angular2 app written in TS #434

Closed
JanHuege opened this issue May 2, 2015 · 28 comments
Closed

Problem loading angular2 app written in TS #434

JanHuege opened this issue May 2, 2015 · 28 comments

Comments

@JanHuege
Copy link

JanHuege commented May 2, 2015

GET http://localhost:8000/angular2/angular2.js
[email protected]:2605 GET https://registry.jspm.io/scripts/main.js 404 (Not Found)i @ [email protected]:2605$__Object$defineProperty.value @ [email protected]:2780n @ [email protected]:377t @ [email protected]:365$__Object$defineProperty.value @ [email protected]:2779$__global.upgradeSystemLoader.e.fetch @ [email protected]:731$__global.upgradeSystemLoader.e.fetch @ [email protected]:1754$__global.upgradeSystemLoader.e.fetch @ [email protected]:1851(anonymous function) @ [email protected]:1525D @ [email protected]:1183I @ [email protected]:11427.O.when @ [email protected]:9307.w.run @ [email protected]:8213.e._drain @ [email protected]:973.e.drain @ [email protected]:62t @ [email protected]:268
[email protected]:140 Potentially unhandled rejection [3] Error loading "scripts/main" at https://registry.jspm.io/scripts/main.js
Not Found: https://registry.jspm.io/scripts/main.js (WARNING: non-Error used)

Why is the uri for my main.js set to "https://registry.jspm.io/scripts/main.js"?
Where does this error come from and how to resovle it?

I am using the newest angular2 release and typescript 1.5beta.

@MajorBreakfast
Copy link
Contributor

Did you include your config.js? Likely your paths aren't set.

@JanHuege
Copy link
Author

JanHuege commented May 2, 2015

How would I write that? Sry I am just starting out with this stuff.
My pathstructure atm is: //build/scripts for all compiled .js files from .ts files and all htmls are in //build

@MajorBreakfast
Copy link
Contributor

GitHub Wiki, YouTube, tests - all should help. What's happening is that systemjs doesn't know where your modules are. BTW take a look at jspm which can generate and update the config for.

@JanHuege
Copy link
Author

JanHuege commented May 2, 2015

Uncaught ReferenceError: require is not defined(anonymous function) @ angular2.js:1
(index):21 Uncaught TypeError: System.import is not a function

I installed jspm and changed the script tags in the header:

<script src="../jspm_packages/system.js"></script> <script src="../config.js"></script>

...

<script src="angular2/angular2.js"></script> <script> System.import('../scripts/main.js'); </script>

System.config({
"baseURL": "/Warenkorb.html",
"transpiler": "traceur",
"paths": {
"": "./build/scripts/.js",
"github:": "jspm_packages/github/.js"
}
});

config.js:

System.config({
"map": {
"traceur": "github:jmcriffey/[email protected]",
"traceur-runtime": "github:jmcriffey/[email protected]"
}
});

I don't get this whole system thing. Since I am using typescript nothing works but the angular2-bundle.js from ngconf2015demo and System.import without any systemconfig or jspm stuff.

@vladima
Copy link
Contributor

vladima commented May 3, 2015

Can you provide more context on what are you trying to do and maybe share the code that shows the problem?

@MajorBreakfast
Copy link
Contributor

Paths should be wildcards
baseURL must be folder, you most likely don't want one anyway

@JanHuege
Copy link
Author

JanHuege commented May 3, 2015

So I use angular2 (npm install angular2), I used angular2-bundle.js from ngconf2015demo before and it worked. With the "normal" angular2 repo I get the errors I posted before on code like this:

todo.ts:

import {Component, View, bootstrap, For, If} from 'angular2/angular2';

@component({
selector: 'todo'
})

@view({
template: <ul> <li *for="#todo of todos"> {{ todo }} </li> </ul> <p> <input #todotext> <button (click)="addTodo(todotext.value)">Add ToDo</button>,
directives: [For]
})

class TodoList{

todos: Array<string>;

constructor(){
    this.todos = ["Eat Breakfast", "Walk Dog", "Breathe"];
}

addTodo(todo: string){
    this.todos.push(todo);
}

doneTyping($event){
    if($event.which === 13){
        this.addTodo($event.target.value);
        $event.target.value = null;
    }
}

}

bootstrap(TodoList);

index.html:

<!doctype html>

<script src="../jspm_packages/system.js"></script>
<script src="../config.js"></script>

<script src="ext_scripts/traceur-runtime.js"></script>
<script src="angular2/angular2.js"></script>
<script> System.import('../scripts/main.js'); </script>

Errors loading this in chrome devtool:

T http://localhost:8080/angular2/angular2-bundle.js
[email protected]:2605 GET https://registry.jspm.io/scripts/todo.js 404 (Not Found)i @ [email protected]:2605$__Object$defineProperty.value @ [email protected]:2780n @ [email protected]:377t @ [email protected]:365$__Object$defineProperty.value @ [email protected]:2779$__global.upgradeSystemLoader.e.fetch @ [email protected]:731$__global.upgradeSystemLoader.e.fetch @ [email protected]:1754$__global.upgradeSystemLoader.e.fetch @ [email protected]:1851(anonymous function) @ [email protected]:1525D @ [email protected]:1183I @ [email protected]:11427.O.when @ [email protected]:9307.w.run @ [email protected]:8213.e._drain @ [email protected]:973.e.drain @ [email protected]:62t @ [email protected]:268
[email protected]:140 Potentially unhandled rejection [3] Error loading "scripts/todo" at https://registry.jspm.io/scripts/todo.js
Not Found: https://registry.jspm.io/scripts/todo.js (WARNING: non-Error used)(anonymous function) @ [email protected]:140i @ [email protected]:167u @ [email protected]:189

@MajorBreakfast
Copy link
Contributor

My advice is to start with something small. Create some files and get them to load. Using systemjs isn't difficult, but you need to roughly understand how everything fits together first. Once you're ready bring angular into the mix.
I say this because above error has nothing to do with angular.
Also keep in mind that ES annotations which your code above uses are an experimental feature which you need to enable first AFAIK.

@JanHuege
Copy link
Author

JanHuege commented May 3, 2015

Uncaught TypeError: Cannot read property 'exports' of undefined
...
Potentially unhandled rejection [2] Error loading "min" at http://localhost:8080/build/scripts/min.js

So atm systemjs loads everything just fine until I start using angular2 and typescript together then I run into these problems with traceur. Everythings loads up just fine but then...

@vladima
Copy link
Contributor

vladima commented May 3, 2015

Ok, I think I know what what is going on.

  1. it is possible to make ngconf demo work with current version of Angular2 that is currently available on npm (2.0.0-alpha.21) however beware that 2.0.0-alpha.21 still uses classes as annotations and this will be changed in the future (in fact it is already changed since angular2-bundle.js uses decorator functions to attach metadata). This means that code in ngconfdemo is now more future proof that it will be if we modify it to use Angular2 2.0.0-alpha.21.
  2. there is one issue in module format detection in SystemJS: 'cjs' format is not recognized when 'module.exports' are used in 'defineProperties' #437

DISCLAIMER: At this point you should be aware that any changes in the demo code will most likely make it non-compatible with future version of Angular2. If you are willing to keep the modified code - be ready to fix it when new version of Angular2 will be avaiable since the code will most likely be broken

First, get a clean copy of ngconf2015demo:

git clone https://github.com/Microsoft/ngconf2015demo.git

Second, install angular2 and its dependencies (rx, zone.js, reflect-metadata). For convinience you can create 'package.json' with the following content

{
    "name": "ngconf2015demo",
    "version": "1.0.0",
    "dependencies": {
        "angular2": "2.0.0-alpha.21",
        "rx": "2.5.2",
        "zonejs": "angular/zone.js",
        "reflect-metadata": "rbuckton/ReflectDecorators"
    }
}

in the root of ngconf2015demo repo and then run:

npm install

NOTE: Currently this code in bundled in 'angular2-bundle.js'.

Version of angular2 from npm uses commonjs however for some modules SystemJS fails to detect the format correctly and loads them as globals. This happens because Traceur converts

export class OpaqueToken {
/// more code here
}

into

Object.defineProperties(module.exports, {
  OpaqueToken: {get: function() {
      return OpaqueToken;
    }},
  __esModule: {value: true}
});
// more code here

and this usage of module.exports is missed by cjsExportsRegex that expects module.exports to be used only in explicit assignments

  // require('...') || exports[''] = ... || exports.asd = ... || module.exports = ...

As a workaround we'll rebuild angular2 to use System.register modules.

Go to 'node_modules/angular2'. First run

npm install

to install dev dependencies for angular2

then

node es6/prod/es5build.js  -s es6/prod/ -d system

this command will run pre-packages script 'es5build.js' that will convert 'angular2' code to 'system' modules and drop results in 'system' folder.

'angular2-bundle.js' already includes both classes for annotations and decorator functions that will attach these annotation to targets. Angular2 2.0.0-alpha.21. has only annotation classes but no decorators meaning that we have to add them. Create a file named 'annotations.ts' in the root of the repo

/// annotations.ts
import {Component as ComponentAnnotation, View as ViewAnnotation} from 'angular2/angular2';

declare module Reflect {
    function getMetadata(metadataKey: string, target: Object): any;
}

function addAnnotation(c: any, annotation: any): any {
    (c.annotations || (c.annotations = [])).push(annotation);
    return c;
}

export function Component(arg?: { selector: string, injectables: any[] }) {
    return (c) => {
        let paramTypes = Reflect.getMetadata("design:paramtypes", c);
        if (paramTypes) {
            c.parameters = paramTypes.map(p => [p]);
        }
        else {
            c.parameters = [];
        }
        addAnnotation(c, new ComponentAnnotation(arg))
        return
    }
}

export function View(arg: { templateUrl: string, directives: any[] }) {
    return c => addAnnotation(c, new ViewAnnotation(arg));
}

Fix 'todo.ts' to use our custom annotations

// replace this line in todo.ts
import {Component, View, bootstrap, For} from 'angular2/angular2';
// with these two lines
import {Component,View} from 'annotations'
import {bootstrap, For} from 'angular2/angular2';

Fix 'firebase/angularfire.js': currently this code in this file correctly picks Component annotation from the "angular2" module and we need to retarget it to the one from "annotations"

// Replace this line
define(["require", "exports", 'angular2/angular2'], function (require, exports, angular2_1) {
// with this line
define(["require", "exports", 'annotations'], function (require, exports, annotations_1) {

// also replace this line
            angular2_1.Component(), 
// with this line
            annotations_1.Component(), 

Finally make changes in 'index.html'

  1. remove script tag for the 'angular2-bundle.js'
  2. add script tags for 'reflect.js' and 'zone.js' as last items in the list.
    <script src="node_modules/reflect-metadata/reflect.js"></script>
    <script src="/node_modules/zone.js/zone.js"></script>
  1. add entries to System.paths for correct path resolution:
        System.paths = {
            '*': '*.js',
            'angular2/*': 'node_modules/angular2/system/*.js',
            'rx/*': 'node_modules/rx/*.js',
        };

Almost done, what is left is adding 'annotations.ts' into 'tsconfig.json' and compiling '.ts' -> '.js'

node tsc/tsc.js

Errors from tsc can be ignored since we don't have proper typing for Angular2 2.0.0-alpha.21.

Run

http-server -o

everything should work.

@JanHuege
Copy link
Author

JanHuege commented May 3, 2015

Okay thanks a lot for your time. I'll try this out as soon as I can.
Tomorrow I hope.

Thanks again. I'll let you know if it worked.

@friktor
Copy link

friktor commented May 6, 2015

@vladima your idea isnt work. (

"Potentially unhandled rejection [2] Component/<@http://0.0.0.0:8080/annotations.js:8:30
__decorate/<@http://0.0.0.0:8080/todo.js:4:77
__decorate@http://0.0.0.0:8080/todo.js:4:1
AngularFire<@http://0.0.0.0:8080/firebase/angularfire.js:20:23
@http://0.0.0.0:8080/firebase/angularfire.js:13:24
a/c.execute@https://jspm.io/[email protected]:5:14414
f@https://jspm.io/[email protected]:5:5926
f@https://jspm.io/[email protected]:5:5898
l@https://jspm.io/[email protected]:5:4563
n/e.instantiate/</<.execute@https://jspm.io/[email protected]:5:8149
h@https://jspm.io/[email protected]:1:19109
m@https://jspm.io/[email protected]:1:19483
l@https://jspm.io/[email protected]:1:16727
c@https://jspm.io/[email protected]:1:17186
i/</<@https://jspm.io/[email protected]:1:15317
run@http://0.0.0.0:8080/node_modules/zone.js/zone.js:93:16
zoneBoundFn@http://0.0.0.0:8080/node_modules/zone.js/zone.js:70:14
D@https://jspm.io/[email protected]:1:7437
I@https://jspm.io/[email protected]:1:7071
[7]</</</</O.prototype.when@https://jspm.io/[email protected]:1:10745
[7]</</</</w.prototype.run@https://jspm.io/[email protected]:1:9779
[3]</</</e.prototype._drain@https://jspm.io/[email protected]:1:1725
e/this.drain@https://jspm.io/[email protected]:1:1392
t@https://jspm.io/[email protected]:1:3302
"```

@vladima
Copy link
Contributor

vladima commented May 6, 2015

@friktor ok, can you share your code in its current state (when it is not working) so I can take a look?

@friktor
Copy link

friktor commented May 6, 2015

@friktor
Copy link

friktor commented May 6, 2015

@vladima the components of the angular boot normally. And System.js works fine, but on the anotation.ts swears.

@vladima
Copy link
Contributor

vladima commented May 6, 2015

@friktor for some reason in your repo I don't see any .js files including 'tsc/tsc.js', 'firebase/firebase.js' and 'firebase/angularfire.js' and as a consequence nothing will work. If I copy them from the original ngconfdemo repo and make necessary changes in 'angularfire.js' - demo works like charm

@guybedford
Copy link
Member

Closing, but feel free to continue discussion.

@ghost
Copy link

ghost commented May 26, 2015

hi,
just i make step by step from
https://angular.io/docs/js/latest/quickstart.html
and as i see it similar
Where is problem?

Test also from ngconf...same
Thanks

@Tooa
Copy link

Tooa commented Jun 3, 2015

Hi,
I had similar problems and was finally able to solve it. Take a look at my angularjs playground. It's a working version of the quickstart tutorial. Maybe it could help you.

@Serhioromano
Copy link

I have the same problem. Here are the errors I have.

And that is strange. I am using JSPM to install angular2. Here is my index.html

<html>
  <head>
    <title>Angular 2 Quickstart</title>
    <script src="assets/jspm/github/jmcriffey/[email protected]/traceur-runtime.js"></script>
  </head>
  <body>

    <my-app></my-app>

    <script src="assets/jspm/system.js"></script>
    <script src="config.js"></script>
  <script src="https://code.angularjs.org/2.0.0-alpha.23/angular2.dev.js"></script>
    <script>
  System.import('build/app');
  </script>
  </body>
</html>

and here is my app.ts

import {Component, View, bootstrap} from 'angular2';

@Component({
  selector: 'my-app'
})
@View({
  template: '<h1>Hello {{ name }}</h1>'
})
// Component controller
class MyAppComponent {
  name: string;

  constructor() {
    console.log(123);
    this.name = 'Alice';
  }
}

bootstrap(MyAppComponent);

And this works just fine. But as soon as I delete this

<script src="https://code.angularjs.org/2.0.0-alpha.23/angular2.dev.js"></script>

I get those errors. Although in the log I can see that all JS files loaded correctly. I suspect that there is something missing that is installed with JSPM and decorators are not supported.

When I use http-server -o to run my app I can see in the log loaded files.

If I delete angular from jspm then it also works fine. I think that https://code.angularjs.org/2.0.0-alpha.23/angular2.dev.js is a bundle that contains everything but when you install with JSPM something is missing.

@guybedford
Copy link
Member

I've posted an issue at jspm/registry#432 for getting Angular2 to work. The instructions I've provided there will work fine for now though too.

@robwormald
Copy link

@nschipperbrainsmith
Copy link

@robwormald Ah thank you for your detailed explanation / guide

@jimthedev
Copy link

I am following @robwormald's instructions above and it works great for dev mode (no bundling) and for regular bundling (to dist/main.js). The problem is when trying to bundle an sfx. I get the following error:

Uncaught Module zone.js not present.load @ main.sfx.js:321linkDeclarativeModule @ main.sfx.js:174link @ main.sfx.js:111load @ main.sfx.js:325(anonymous function) @ main.sfx.js:358(anonymous function) @ angular2.js:22loader @ main.sfx.js:339(anonymous function) @ angular2.js:22

Oddly the sourcemap is generated and it points back correctly to [email protected].

I am using Typescript as my transpiler.

My config.js looks like this:

System.config({
  "baseURL": "/",
  "defaultJSExtensions": true,
  "transpiler": "typescript",
  "typescriptOptions": {
    "module": "commonjs",
    "emitDecoratorMetadata": true
  },
  "paths": {
    "github:*": "lib/github/*",
    "npm:*": "lib/npm/*",
    "app": "src"
  },
  "packages": {
    "app": {
      "main": "main",
      "defaultExtension": "ts"
    }
  }
});

System.config({
  "map": {
    "angular2": "npm:[email protected]",
    "es6-shim": "github:es-shims/[email protected]",
    "reflect-metadata": "npm:[email protected]",
    "typescript": "github:mhegazy/[email protected]",
    "zone.js": "npm:[email protected]",
    "github:jspm/[email protected]": {
      "assert": "npm:[email protected]"
    },
    "github:jspm/[email protected]": {
      "path-browserify": "npm:[email protected]"
    },
    "github:jspm/[email protected]": {
      "process": "npm:[email protected]"
    },
    "github:jspm/[email protected]": {
      "url": "npm:[email protected]"
    },
    "github:jspm/[email protected]": {
      "util": "npm:[email protected]"
    },
    "npm:[email protected]": {
      "fs": "github:jspm/[email protected]",
      "path": "github:jspm/[email protected]",
      "process": "github:jspm/[email protected]",
      "reflect-metadata": "npm:[email protected]",
      "rx": "npm:[email protected]",
      "url": "github:jspm/[email protected]",
      "zone.js": "npm:[email protected]"
    },
    "npm:[email protected]": {
      "util": "npm:[email protected]"
    },
    "npm:[email protected]": {
      "util": "github:jspm/[email protected]"
    },
    "npm:[email protected]": {
      "process": "github:jspm/[email protected]"
    },
    "npm:[email protected]": {
      "process": "github:jspm/[email protected]"
    },
    "npm:[email protected]": {
      "assert": "github:jspm/[email protected]"
    },
    "npm:[email protected]": {
      "process": "github:jspm/[email protected]"
    },
    "npm:[email protected]": {
      "assert": "github:jspm/[email protected]",
      "punycode": "npm:[email protected]",
      "querystring": "npm:[email protected]",
      "util": "github:jspm/[email protected]"
    },
    "npm:[email protected]": {
      "inherits": "npm:[email protected]",
      "process": "github:jspm/[email protected]"
    },
    "npm:[email protected]": {
      "process": "github:jspm/[email protected]"
    }
  }
});

My package.js looks like this:

{
  "jspm": {
    "directories": {
      "baseURL": "www",
      "packages": "www/lib"
    },
    "dependencies": {
      "angular2": "npm:angular2@^2.0.0-alpha.27",
      "es6-shim": "github:es-shims/es6-shim@^0.32.2",
      "reflect-metadata": "npm:reflect-metadata@^0.1.0",
      "zone.js": "npm:zone.js@^0.5.1"
    },
    "devDependencies": {
      "typescript": "github:mhegazy/[email protected]"
    }
  }
}

And main.html looks like this:

<html>
<head>
    <title>Demo App</title>
    <script src="dist/main.sfx.js"></script>
</head>
<body>
    <!-- our angular2 component -->
    <test-app>
        Loading...
    </test-app>
</body>
</html>

@jimthedev
Copy link

Per @robwormald in jspm/registry#432 (comment) it looks like the bundling issue is being tracked in systemjs/builder#206 and microsoft/TypeScript#2233 (comment)

My impression is that basically SystemJS needs to throw an error since bundling is not currently supported in TypeScript.

@vance
Copy link

vance commented May 20, 2016

The quickstart guide has a bug and will not show the systemjs.config.js file. Linked: angular/angular#8755

@zohaibkathwari
Copy link

zohaibkathwari commented Jan 26, 2017

Well in my case the error is coming from systemjs fetch method i guess, its stated at the end of these files:

Customer.ts file:

import {Address} from './src/Address'

export class Customer {

public address: Address = new Address();

private _customerName: string = "";

public set CustomerName (name: string) {
    if (name.length == 0) {
        throw "Customer name cannot be empty";
    }
    this._customerName = name;
}

public get CustomerName(): string {
    return this._customerName;
}

Validate (): void {
    alert('validated sire!');
}

}


Address.ts file:
export class Address {
public streetName: string = "olaaaas";
}


<script src="node_modules/systemjs/dist/system.js"></script>
<script>
    System.config({
        "defaultExtension": 'js'
    });

    System.import('./Customer.js').then(function (exports) {
        var cust = new exports.Customer();
        console.log('exports: ', cust);
    }).catch(function(error){
        console.log(error);
    });
</script>
_________________________________________________________________________________

Error from System.imports Catch method on google chrome console:

GET http://localhost:8000/src/Address 404 (Not Found) @ fetch.js:32
(anonymous) @ instantiate.js:157
Error: Fetch error: 404 Not Found
Instantiating http://localhost:8000/src/Address
Loading http://localhost:8000/Customer.js
Loading ./Customer.js
at fetch.js:37


Would require a little help for the above mentioned error.

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