Angular 2/Typescript: require not found

1.3k views Asked by At

I am trying to get the angular 2 example running with a gulp typescript compiler. The gulp-script compiles

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

to

var angular2_1 = require("angular2/angular2")

which does not run in the browser. What is wrong with this? As far as I know, this kind of implementation of 'require' is only used with nodeJS. Why does the TypeScript compiler still compile it like that?

Anyone any ideas?

Kind regards

2

There are 2 answers

1
unobf On BEST ANSWER

I was not able to get that working but was able to get it working with gulp-traceur. Here is my gulpfile.

var gulp = require('gulp');
var gulpTraceur = require('gulp-traceur');
var through2 = require('through2');
var gutil = require('gulp-util');
var sourcemaps = require('gulp-sourcemaps');
var copy = require('gulp-copy');

gulp.task('compile',function() {
  return gulp.src("./*.es6.js")
    .pipe(sourcemaps.init())
    .pipe(gulpTraceur({
        sourceMaps: true,
        outputLanguage: 'es5',
        annotations: true, // parse annotations
        types: true, // parse types
        script: false, // parse as a module
        memberVariables: true, // parse class fields
        modules: 'instantiate'
    }))
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest('dist'));
});

gulp.task('copy', function () {
    return gulp.src(['*.html', '*.css'])
        .pipe(copy('dist'));
});

gulp.task('watch', function () {
    gulp.watch(['*.html', '*.css', './*.es6.js'], ['compile', 'copy']);
});


gulp.task('default', ['compile', 'copy', 'watch']);

The project can be seen here:

https://github.com/dylanb/Axponents/tree/master/angular2

0
Ajden Towfeek On

That's because you're compiling the typescript files for being served up by node by passing commonjs to the --module flag or just -m.

You can also pass in amd:

> tsc.cmd -m amd -t es5 --emitDecoratorMetadata app.ts

which will produce the folloing js:

define(["require", "exports", "angular2/angular2"], function (require, exports, angular2_1)

Otherwise, if you just want it to work as in their examples install the http-server module and serve the page.

> npm install -g http-server
> http-server

And visit

localhost:8080/index.html