美文网首页ng2
webpack打包ng2 英雄指南

webpack打包ng2 英雄指南

作者: 檀木丁 | 来源:发表于2016-11-03 13:14 被阅读1528次

    概述

    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页面,不用引入 <script>, <link>之类的,借助插件依赖库等,就能自动插入到目标js中。所以,最后的【英雄指南】index.html内容很少。

    <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就是!

    相关文章

      网友评论

      • 7b722bb93670:angular2官网的种子文件目录不是这样的e2e怎么办

      本文标题:webpack打包ng2 英雄指南

      本文链接:https://www.haomeiwen.com/subject/icubuttx.html