Skip to content
Rupesh Tiwari edited this page Mar 17, 2017 · 2 revisions

Welcome to setup

Here we will see how make your project ready for angular 2, typescript, jasmine, karma ready.

Enabled NPM

  • Create an empty asp.net project run below command to enable node js.
npm init -f

-f is alias of force

  • It will create package.json file in your project.
{
  "name": "sample",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

Installing Angular2 Dependencies

  • Run below command to install node_module folder which will have all of below javascript files.
npm i -S @angular/common @angular/compiler @angular/core @angular/platform-browser @angular/platform-browser-dynamic es6-shim reflect-metadata rxjs@5.0.0-beta.6 zone.js
  • i is an alias for install, -S is an alias for --save.
  • i or install they install the javascript files under node_module folder.
  • -S or --save command updates the package.json file also.
  • after installation done you will see package.json updated like below
 "dependencies": {
    "@angular/common": "^2.4.9",
    "@angular/compiler": "^2.4.9",
    "@angular/core": "^2.4.9",
    "@angular/platform-browser": "^2.4.9",
    "@angular/platform-browser-dynamic": "^2.4.9",
    "es6-shim": "^0.35.3",
    "reflect-metadata": "^0.1.10",
    "rxjs": "^5.0.0-beta.6",
    "zone.js": "^0.7.7"
  }

Install Typescript Dependencies

  • install below:
    • typescript
    • tslint
    • type definitions
    • In order to install above 3 things run below command
npm i -D typescript tslint typings

-D is an alias for --save-dev

After installing them u will see your node_module folder got updated with some new folders. Also package.json gets updated with devDependencies ("devDependencies": these packages are only needed for development and testing)

"devDependencies": {
    "tslint": "^4.5.1",
    "typescript": "^2.2.1",
    "typings": "^2.1.0"
  }

Webpack Dependencies

Install webpack and its other loaders and plugins needed for angular 2. Run below command

npm i -D webpack webpack-dev-server html-webpack-plugin raw-loader ts-loader tslint-loader

It will install webpack and it's dev dependencies.

"devDependencies": {
    "html-webpack-plugin": "^2.28.0",
    "raw-loader": "^0.5.1",
    "ts-loader": "^2.0.1",
    "tslint": "^4.5.1",
    "tslint-loader": "^3.4.3",
    "typescript": "^2.2.1",
    "typings": "^2.1.0",
    "webpack": "^2.2.1",
    "webpack-dev-server": "^2.4.1"
  }

Unit Testing Dependencies

  • Installing Karma , jasmine, phantomjs,

npm i -D karma karma-jasmine jasmine-core karma-chrome-launcher karma-phantomjs-launcher phantomjs-prebuilt karma-sourcemap-loader karma-webpack

  • It will update your package.json devDependencies
 "devDependencies": {
    "html-webpack-plugin": "^2.28.0",
    "jasmine-core": "^2.5.2",
    "karma": "^1.5.0",
    "karma-chrome-launcher": "^2.0.0",
    "karma-jasmine": "^1.1.0",
    "karma-phantomjs-launcher": "^1.0.2",
    "karma-sourcemap-loader": "^0.3.7",
    "karma-webpack": "^2.0.2",
    "phantomjs-prebuilt": "^2.1.14",
    "raw-loader": "^0.5.1",
    "ts-loader": "^2.0.1",
    "tslint": "^4.5.1",
    "tslint-loader": "^3.4.3",
    "typescript": "^2.2.1",
    "typings": "^2.1.0",
    "webpack": "^2.2.1",
    "webpack-dev-server": "^2.4.1"
  }

Configurations

Type Definitions

First we need typing.json file where we put all typings that we want to install. For that run below command.

./node_modules/.bin/typings init

After runing above command you will see typing.json file is added to your project.

{
  "name": "sample",
  "dependencies": {}
}
  • Now Let's install typescript definitions for below libraries. We are using Typings to install type definitions.

    • nodejs
    • jasmine
    • es6-promise
  • Run below command for jasmine and node.

    ./node_modules/.bin/typings install dt~jasmine env~node --save --global

  • We'll run a second install command for the es6-promise shim.

    ./node_modules/.bin/typings install es6-promise --save

  • Then you will typings.json will be updated as below:

{
  "name": "sample",
  "dependencies": {},
  "globalDependencies": {
    "jasmine": "registry:dt/jasmine#2.5.0+20170207112528",
    "node": "registry:env/node#6.0.0+20170213133316"
  }
}

Configuring TsLint

Add tslit.json file in the root of project and add below json

{
    "class-name": true,
    "comment-format": [
        true,
        "check-space"
    ],
    "indent": [
        true,
        "spaces"
    ],
    "no-duplicate-variable": true,
    "no-eval": true,
    "no-internal-module": true,
    "no-trailing-whitespace": true,
    "no-var-keyword": true,
    "one-line": [
        true,
        "check-open-brace",
        "check-whitespace"
    ],
    "quotemark": [
        true,
        "single"
    ],
    "semicolon": true,
    "triple-equals": [
        true,
        "allow-null-check"
    ],
    "typedef-whitespace": [
        true,
        {
            "call-signature": "nospace",
            "index-signature": "nospace",
            "parameter": "nospace",
            "property-declaration": "nospace",
            "variable-declaration": "nospace"
        }
    ],
    "variable-name": [
        true,
        "ban-keywords",
        "check-format"
    ],
    "whitespace": [
        true,
        "check-branch",
        "check-decl",
        "check-operator",
        "check-separator",
        "check-type"
    ]
}

TypeScript Configuration

The TypeScript compiler requires a configuration file, tsconfig.json lets add this file and paste below json

{
    "compilerOptions": {
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "module": "commonjs",
        "moduleResolution": "node",
        "noImplicitAny": true,
        "suppressImplicitAnyIndexErrors": true,
        "removeComments": false,
        "sourceMap": true,
        "target": "es5"
    },
    "exclude": [
        "node_modules",
        "typings/main",
        "typings/main.d.ts"
    ]
}

Configuring Karma

  • Create a directory named karma in the root of your project. Copy the json as mentioned in project.
  • Add karma.conf.js ( In this file We describe which file and how it should be tested) copy below code and paste it.
'use strict';

module.exports =  function(config) {
    config.set({
        autoWatch: true,
        browsers: ['Chrome', 'PhantomJS'],
        files: [
            '../node_modules/es6-shim/es6-shim.min.js',
            'karma.entry.js'
        ],
        frameworks: ['jasmine'],
        logLevel: config.LOG_INFO,
        phantomJsLauncher: {
            exitOnResourceError: true
        },
        port: 9876,
        preprocessors: {
            'karma.entry.js': ['webpack', 'sourcemap']
        },
        reporters: ['dots'],
        singleRun: true,
        webpack: require('../webpack/webpack.test.js'),
        webpackServer: {
            noInfo: true
        }
    });
};
  • Add karma.entry.js (In this file We will describe setup for angular2 and webpack ) copy below code and paste it.
require('es6-shim');
require('reflect-metadata');
require('zone.js/dist/zone');
require('zone.js/dist/long-stack-trace-zone');
require('zone.js/dist/async-test');
require('zone.js/dist/fake-async-test');
require('zone.js/dist/sync-test');
require('zone.js/dist/proxy');
require('zone.js/dist/jasmine-patch');

const browserTesting = require('@angular/platform-browser-dynamic/testing');
const coreTesting = require('@angular/core/testing');
const context = require.context('../src/', true, /\.spec\.ts$/);

Error.stackTraceLimit = Infinity;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 2000;

coreTesting.TestBed.resetTestEnvironment();
coreTesting.TestBed.initTestEnvironment(
    browserTesting.BrowserDynamicTestingModule,
    browserTesting.platformBrowserDynamicTesting()
);

Configuring Webpack

  • In your project directory, create a sub-directory named webpack, which will house both of these files.
  • we will have just a webpack.dev.js and a webpack.test.js. The .dev configuration will be used when spinning up the Webpack development server so that we can see our application in the browser.

Setting up webpack.test.js

  • Create webpack.test.js inside webpack folder.
  • put below json as it is my github sourcecode.
'use strict';

const path = require('path');
const webpack = require('webpack');

module.exports = {
    devtool: 'inline-source-map',
    module: {
        preLoaders: [
            { exclude: /node_modules/, loader: 'tslint', test: /\.ts$/ }
        ],
        loaders: [
            { loader: 'raw', test: /\.(css|html)$/ },
            { exclude: /node_modules/, loader: 'ts', test: /\.ts$/ }
        ]
    },
    resolve: {
        extensions: ['', '.js', '.ts'],
        modulesDirectories: ['node_modules'],
        root: path.resolve('.', 'src')
    },
    tslint: {
        emitErrors: true
    }
};
  • create webpack.dev.js
'use strict';

const HtmlWebpack = require('html-webpack-plugin');
const path = require('path');
const webpack = require('webpack');
const ChunkWebpack = webpack.optimize.CommonsChunkPlugin;

const rootDir = path.resolve(__dirname, '..');

module.exports = {
    debug: true,
    devServer: {
        contentBase: path.resolve(rootDir, 'dist'),
        port: 9000
    },
    devtool: 'source-map',
    entry: {
        app: [ path.resolve(rootDir, 'src', 'bootstrap') ],
        vendor: [ path.resolve(rootDir, 'src', 'vendor') ]
    },
    module: {
        loaders: [
            { loader: 'raw', test: /\.(css|html)$/ },
            { exclude: /node_modules/, loader: 'ts', test: /\.ts$/ }
        ]
    },
    output: {
        filename: '[name].bundle.js',
        path: path.resolve(rootDir, 'dist')
    },
    plugins: [
        new ChunkWebpack({
            filename: 'vendor.bundle.js',
            minChunks: Infinity,
            name: 'vendor'
        }),
        new HtmlWebpack({
            filename: 'index.html',
            inject: 'body',
            template: path.resolve(rootDir, 'src', 'index.html')
        })
    ],
    resolve: {
        extensions: [ '', '.js', '.ts' ]
    }
};