Webpack打包 ng2英雄指南

本文首發簡書 http://www.jianshu.com/p/f5a21f18cfae, 歡迎轉載,但請註明轉載鏈接,謝謝!

概述

ng2英雄指南相關問題 這篇記錄的是在實操 英雄指南過程中遇到的問題以及解決方法,後來在社區中詢問 【雪狼】, 實際開發ng過程中一般使用哪種成熟打包配置工具,被告知可以使用 webpack, Angular-CLI。 經過查看幾個github ng2入門項目,確實是用webpack打包。所以,就倒騰 如何在 英雄指南中使用webapck, 官方使用的是SystemJS。

如有對webpack不清楚的,強烈建議參考 中文官方文檔 WEBPACK簡介 或者按照我的例子實操下 Angular2開發基礎之Webpack

完整代碼 -> ng2-tour-of-heroes項目

webpack打包 英雄指南

Angular2開發基礎之Webpack講解了如何配置基本的webpack.config.js, 然而,在【英雄指南】完成到最後,內容繁多,ts, css, html各種文件,如何把css, html等文件也打包進入webpack中呢? 這就需要新的配置了。

package.json

相比之前的package.json, 內容有很大變化。

"scripts": {
    "build": "webpack --progress",
    "build:prod": "webpack -p --progress",
    "postinstall": "typings install",
    "server": "webpack-dev-server --inline --progress"
  }

刪除 “dependencies”: 中的systemjs相關內容, “devDependencies”中添加新依賴庫

"devDependencies": {
    "angular2-template-loader": "^0.4.0",
    "awesome-typescript-loader": "^2.2.4",
    "css-loader": "^0.23.1",
    "extract-text-webpack-plugin": "^1.0.1",
    "html-loader": "^0.4.3",
    "raw-loader": "^0.5.1",
    "style-loader": "^0.13.1",
    "html-webpack-plugin": "^2.24.1",
    "ts-loader": "^0.9.5",
    "typescript": "^2.0.3",
    "typings": "^1.4.0",
    "webpack": "^1.13.3",
    "webpack-dev-server": "^1.16.2"
  }

安裝依賴庫

npm install

目錄更新

原本的英雄指南目錄是在一個app目錄中的,但是要稍微區分下,修改後的目錄結構如下:
目錄更新

其中app目錄包含了【英雄指南】中的所ts, css, html文件。

webpack.config.js

千呼萬喚纔出來-webpack.config.js, 強烈推薦查看 ng2中文官方文檔!Webpack簡介 其中有詳細的說明。
針對 【英雄指南】,只需要簡化點的配置。

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

var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {

    entry: './src/app/main.ts',
    output: {
        path: root('dist'),
        filename: 'app.bundle.js'
    },
    resolve: {
        extensions: ['', '.js', '.ts']
    },
    module: {
        loaders: [
            {
                test: /\.ts$/,
                loaders: ['awesome-typescript-loader', 'angular2-template-loader']
            },
            {
                test: /\.css$/,
                exclude: root('src', 'app'),
                loader: ExtractTextPlugin.extract({fallbackLoader: 'style-loader', loader: ['css']})
            },

            // all css required in src/app files will be merged in js files
            {
                test: /\.css$/,
                include: root('src', 'app'),
                loader: 'raw'
            },

            // support for .html as raw text
            {
                test: /\.html$/,
                loader: 'raw',
                exclude: root('src', 'index.html'),
                include: root('src', 'app')
            }
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: './src/index.html'
        }),
        new ExtractTextPlugin({filename: 'css/[name].[hash].css'})
    ]
};

// Helper functions
function root(args) {
    args = Array.prototype.slice.call(arguments, 0);
    return path.join.apply(path, [__dirname].concat(args));
}

去除system.js

moudleId

要webpack正常打包,還需要清除systemjs的東西,如index.html中的鏈接,以及app/xxx.ts中的moudle.id。
原因是SystemJS和Webpack處理ng2的文件相對路徑是不一樣的。
之前的 【英雄指南】中某個 app.dashborad.component.ts中會存在 moudle.id,但是webpack就不需要這個了。
參考 相對於組件的路徑

Webpack: 加載模板和樣式表
Webpack 開發者可以採用 moduleId 的另一個替代方案。通過讓組件元數據的 template 和 styles / styleUrls 屬性以 ./ 開頭,並使其指向相對於組件的 URL ,可以在運行期間爲它們加載模板和樣式表。

import { Component } from '@angular/core';

import '../../public/css/styles.css';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent { }

index.html

使用Webpack可以讓index頁面,不用引入

<html>
<head>
    <base href="/">
    <title>Angular2 QuickStart</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>

<body>
<my-app>Loading...</my-app>
</body>
</html>

dist目錄中的index.html會添加相關的 引用。

<script type="text/javascript" src="app.bundle.js"></script></body>

運行應用

上述改造完成!需要編譯檢驗效果。

啓動server

npm run server

編譯完成,沒出現錯誤後,在瀏覽器中輸入 http://localhost:8080/ 就能看到效果。而且,你修改ts文件後就會自動編譯,自動reload頁面。
注意,使用webpack-dev-server是不會編譯dist目錄的,是在內存中生成運行的,不在磁盤上。

生成dist

npm run build  / npm run build:prod

生成的dist目錄,只有兩個文件 app.bundle.js, index.html 其他的都不見,app目錄中的html,css都在js中。
你可根據需求配置。
但是有個小問題,在dist中直接打開Index.html 只會顯示 【Loading …】, F12調試發現,錯誤顯示,沒有找到app.bundle.js, 這個有點奇怪。有知道的同學,告知一下,如何在目標文件中,直接打開index.html正確顯示內容!

代碼

老地方, 其中ng2-tour-of-heroes就是!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章