Webpack 简介

Webpack is a popular module bundler, a tool for bundling application source code in convenient chunks and for loading that code from a server into a browser.

Webpack是一个广受欢迎的模块打包器, 这个工具用来把程序源码打包到一些方便易用的中,以便把这些代码从服务器加载到浏览器中。

It's an excellent alternative to the SystemJS approach we use throughout the documentation. In this guide we get a taste of Webpack and how to use it with Angular applications.

它是我们在文档中到处使用的SystemJS的一个优秀替代品。这篇指南会带我们尝尝Webpack的滋味,并学习如何在Angular程序中使用它。

Table of contents

目录

What is Webpack?

什么是Webpack?

Configuring Webpack

配置Webpack

Trying it out

试一下

Conclusions

总结

What is Webpack?

什么是Webpack?

Webpack is a powerful module bundler. A bundle is a JavaScript file that incorporate assets that belong together and should be served to the client in a response to a single file request. A bundle can include JavaScript, CSS styles, HTML, and almost any other kind of file.

Webpack是一个强力的模块打包器。 所谓包(bundle)就是一个JavaScript文件,它把一堆资源(assets)合并在一起,以便它们可以在同一个文件请求中发回给客户端。 包中可以包含JavaScript、CSS样式、HTML以及很多其它类型的文件。

Webpack roams over your application source code, looking for import statements, building a dependency graph, and emitting one (or more) bundles. With plugin "loaders" Webpack can preprocess and minify different non-JavaScript files such as TypeScript, SASS, and LESS files.

Webpack会遍历你应用中的所有源码,查找import语句,构建出依赖图谱,并产出一个(或多个)。 通过“加载器(loaders)”插件,Webpack可以对各种非JavaScript文件进行预处理和最小化(Minify),比如TypeScript、SASS和LESS文件等。

We determine what Webpack does and how it does it with a JavaScript configuration file, webpack.config.js.

我们通过一个JavaScript配置文件webpack.config.js来决定Webpack做什么以及如何做。

Entries and outputs

入口与输出

We feed Webpack with one or more entry files and let it find and incorporate the dependencies that radiate from those entries. In this example, we start from the application's root file, src/app.ts:

我们给Webpack提供一个或多个入口文件,来让它查找与合并那些从这些入口点发散出去的依赖。 在下面这个例子中,我们的入口点是该应用的根文件src/app.ts

webpack.config.js (single entry)

entry: { app: 'src/app.ts' }

Webpack inspects that file and traverses its import dependencies recursively.

Webpack探查那个文件,并且递归遍历它的import依赖。

src/app.ts

import { Component } from '@angular/core'; @Component({ ... }) export class AppComponent {}

Here it sees that we're importing @angular/core so it adds that to its dependency list for (potential) inclusion in the bundle. It opens @angular/core and follows its network of import statements until it has build the complete dependency graph from app.ts down.

这里,Webpack看到我们正在导入@angular/core,于是就这个文件加入到它的依赖列表里,为(有可能)把该文件打进包中做准备。 它打开@angular/core并追踪由该文件的import语句构成的网络,直到构建出从app.ts往下的整个依赖图谱。

Then it outputs these files to the app.js bundle file designated in configuration:

然后它把这些文件输出到当前配置所指定的包文件app.js中:

webpack.config.js (single output)

output: { filename: 'app.js' }

This app.js output bundle is a single JavaScript file that contains our application source and its dependencies. We'll load it later with a <script> tag in our index.html.

这个app.js输出包是个单一的JavaScript文件,它包含程序的源码及其所有依赖。 后面我们将在index.html中用<script>标签来加载它。

Multiple bundles

多重包

We probably do not want one giant bundle of everything. We'll likely prefer to separate our volatile application app code from comparatively stable vendor code modules.

我们可能不会希望把所有东西打进一个巨型包,而更喜欢把多变的应用代码从相对稳定的第三方提供商模块中分离出来。

We change the configuration so that we have two entry points, app.ts and vendor.ts:

所以要修改配置,以获得两个入口点:app.tsvendor.ts

webpack.config.js (two entries)

entry: { app: 'src/app.ts', vendor: 'src/vendor.ts' }, output: { filename: '[name].js' }

Webpack constructs two separate dependency graphs and emits two bundle files, one called app.js containing only our application code and another called vendor.js with all the vendor dependencies.

Webpack会构造出两个独立的依赖图谱,并产出两个包文件:一个叫做app.js,它只包含我们的应用代码;另一个叫做vendor.js,它包含所有的提供商依赖。

The [name] in the output name is a Webpack placeholder that is replaced with the entry names. app and vendor respectively.

在输出文件名中出现的[name]是一个Webpack的占位符,它将被替换为入口点的名字,分别是appvendor

We need a plugin to make this work; we'll cover that later in the chapter.

我们需要一个插件来完成此项工作,本章后面的部分会覆盖它。

We met app.ts earlier. We wrote vendor.ts such that it imports the vendor modules we need:

我们以前见过app.ts,就不再赘述了。还要再写一个vendor.ts,让它导入我们要用的提供商模块:

src/vendor.ts

// Angular import '@angular/platform-browser'; import '@angular/platform-browser-dynamic'; import '@angular/core'; import '@angular/common'; import '@angular/http'; import '@angular/router'; // RxJS import 'rxjs'; // Other vendors for example jQuery, Lodash or Bootstrap // You can import js, ts, css, sass, ...

Loaders

加载器(Loader)

Webpack can bundle any kind of file: JavaScript, TypeScript, CSS, SASS, LESS, images, html, fonts, whatever. Webpack itself doesn't know what to do with a non-JavaScript file. We teach it to process such files into JavaScript with loaders. Here we configure loaders for TypeScript and CSS:

Webpack可以打包任何类型的文件:JavaScript、TypeScript、CSS、SASS、LESS、图片、HTML以及字体文件等等。 Webpack本身并不知道该如何处理这些非JavaScript文件。 我们要通过加载器来告诉它如何把这些文件处理成JavaScript文件。 在这里,我们为TypeScript和CSS文件配置了加载器。

webpack.config.js (two entries)

loaders: [ { test: /\.ts$/ loaders: 'ts' }, { test: /\.css$/ loaders: 'style!css' } ]

As Webpack encounters import statements like these ...

当Webpack遇到像这样的import语句时……

import { AppComponent } from './app.component.ts'; import 'uiframework/dist/uiframework.css';

... it applies the test RegEx patterns. When a pattern matches the filename, Webpack processes the file with the associated loader.

……它会使用test后面的正则表达式进行模式匹配。如果一个模式匹配上文件名,Webpack就用它所关联的加载器处理这个文件。

The first import file matches the .ts pattern so Webpack processes it with the awesome-typescript-loader. The imported file doesn't match the second pattern so its loader is ignored.

第一个import文件匹配上了.ts模式,于是Webpack就用awesome-typescript-loader加载器处理它。 导入的文件没有匹配上第二个模式,于是它的加载器就被忽略了。

The second import matches the second .css pattern for which we have two loaders chained by the (!) character. Webpack applies chained loaders right to left so it applies the css loader first (to flatten CSS @import and url(...) statements) and then the style loader (to append the css inside <style> elements on the page).

第二个import匹配上了第二个.css模式,它有两个用叹号字符(!)串联起来的加载器。 Webpack会从右到左逐个应用串联的加载器,于是它先应用了css加载器(用来平面化CSS的@importurl(...)语句), 然后应用了style加载器(用来把css追加到页面上的<style>元素中)。

Plugins

插件

Webpack has a build pipeline with well-defined phases. We tap into that pipeline with plugins such as the uglify minification plugin:

Webpack有一条构建流水线,它被划分成多个经过精心定义的阶段(phase)。 我们可以把插件(比如uglify代码最小化插件)挂到流水线上:

plugins: [ new webpack.optimize.UglifyJsPlugin() ]

Configure Webpack

配置Webpack

After that brief orientation, we are ready to build our own Webpack configuration for Angular apps.

经过简短的培训之后,我们准备为Angular应用构建一份自己的Webpack配置了。

Begin by setting up the development environment.

从设置开发环境开始。

Create a new project folder

创建一个新的项目文件夹

mkdir angular-webpack cd angular-webpack

Add these files to the root directory:

把下列文件添加到根目录下:

{ "name": "angular2-webpack", "version": "1.0.0", "description": "A webpack starter for Angular", "scripts": { "start": "webpack-dev-server --inline --progress --port 8080", "test": "karma start", "build": "rimraf dist && webpack --config config/webpack.prod.js --progress --profile --bail" }, "license": "MIT", "dependencies": { "@angular/common": "~2.2.0", "@angular/compiler": "~2.2.0", "@angular/core": "~2.2.0", "@angular/forms": "~2.2.0", "@angular/http": "~2.2.0", "@angular/platform-browser": "~2.2.0", "@angular/platform-browser-dynamic": "~2.2.0", "@angular/router": "~3.2.0", "core-js": "^2.4.1", "rxjs": "5.0.0-beta.12", "zone.js": "^0.6.25" }, "devDependencies": { "@types/node": "^6.0.45", "@types/jasmine": "^2.5.35", "angular2-template-loader": "^0.4.0", "awesome-typescript-loader": "^2.2.4", "css-loader": "^0.23.1", "extract-text-webpack-plugin": "^1.0.1", "file-loader": "^0.8.5", "html-loader": "^0.4.3", "html-webpack-plugin": "^2.15.0", "jasmine-core": "^2.4.1", "karma": "^1.2.0", "karma-jasmine": "^1.0.2", "karma-phantomjs-launcher": "^1.0.2", "karma-sourcemap-loader": "^0.3.7", "karma-webpack": "^1.8.0", "null-loader": "^0.1.1", "phantomjs-prebuilt": "^2.1.7", "raw-loader": "^0.5.1", "rimraf": "^2.5.2", "style-loader": "^0.13.1", "typescript": "^2.0.3", "webpack": "^1.13.0", "webpack-dev-server": "^1.14.1", "webpack-merge": "^0.14.0" } } { "compilerOptions": { "target": "es5", "module": "commonjs", "moduleResolution": "node", "sourceMap": true, "emitDecoratorMetadata": true, "experimentalDecorators": true, "removeComments": false, "noImplicitAny": true, "suppressImplicitAnyIndexErrors": true } } module.exports = require('./config/webpack.dev.js'); module.exports = require('./config/karma.conf.js'); var path = require('path'); var _root = path.resolve(__dirname, '..'); function root(args) { args = Array.prototype.slice.call(arguments, 0); return path.join.apply(path, [_root].concat(args)); } exports.root = root;

Many of these files and much of their content should be familiar from other Angular documentation chapters.

这些文件及其内容多数都在其它Angular文档中见过了,应该比较熟悉。

Learn about the package.json in the npm packages chapter. We require packages for Webpack use in addition to the ones listed in that chapter.

要了解package.json,请到npm包一章。 除了那一章列出的包之外,我们还需要用到Webpack的包。

Learn about tsconfig.json in the Typescript configuration chapter.

要了解tsconfig.json,参见Typescript配置一章。

Open a terminal/console window and install the npm packages with npm install.

打开终端/控制台窗口,并通过npm install命令安装这些npm包。

Common Configuration

公共配置

We will define separate configurations for development, production, and test environments. All three have some configuration in common. We'll gather that common configuration in a separate file called webpack.common.js.

我们可以为开发、产品和测试环境定义分别各自的配置文件。 但三者总会有一些公共配置。 于是我们把那些公共的配置收集到一个名叫webpack.common.js的独立文件中。

Let's see the entire file and then walk through it a section at a time:

来看下入口文件,用一个小节的时间了解下它的内容:

config/webpack.common.js

var webpack = require('webpack'); var HtmlWebpackPlugin = require('html-webpack-plugin'); var ExtractTextPlugin = require('extract-text-webpack-plugin'); var helpers = require('./helpers'); module.exports = { entry: { 'polyfills': './src/polyfills.ts', 'vendor': './src/vendor.ts', 'app': './src/main.ts' }, resolve: { extensions: ['', '.ts', '.js'] }, module: { loaders: [ { test: /\.ts$/, loaders: ['awesome-typescript-loader', 'angular2-template-loader'] }, { test: /\.html$/, loader: 'html' }, { test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/, loader: 'file?name=assets/[name].[hash].[ext]' }, { test: /\.css$/, exclude: helpers.root('src', 'app'), loader: ExtractTextPlugin.extract('style', 'css?sourceMap') }, { test: /\.css$/, include: helpers.root('src', 'app'), loader: 'raw' } ] }, plugins: [ new webpack.optimize.CommonsChunkPlugin({ name: ['app', 'vendor', 'polyfills'] }), new HtmlWebpackPlugin({ template: 'src/index.html' }) ] };

Webpack is a NodeJS-based tool so its configuration is a JavaScript commonjs module file that begins with require statements as such files do.

Webpack是一个基于NodeJS的工具,所以它的配置文件就是一个JavaScript的CommonJS模块文件,它像常规写法一样以require语句开始。

The configuration exports several objects, beginning with the entries described earlier:

这个配置项导出了几个对象,从前面说过的入口点(entry)开始:

config/webpack.common.js

entry: { 'polyfills': './src/polyfills.ts', 'vendor': './src/vendor.ts', 'app': './src/main.ts' },

We are splitting our application into three bundles:

我们正在把应用拆成三个包:

Loading polyfills
加载填充物(polyfills)

Load Zone.js early, immediately after the other ES6 and metadata shims.

早点加载Zone.js,紧跟在其它ES6和metadata垫片(shim)之后。

Our app will import dozens if not hundreds of JavaScript and TypeScript files. We might write import statements with explicit extensions as in this example:

本程序将需要import十多个(如果不是上百个的话)JavaScript和TypeScript文件。 我们可以带着明确的扩展名来写这些import语句,就像下面的例子中这样:

import { AppComponent } from './app.component.ts';

But most of our import statements won't mention the extension at all. So we tell Webpack to resolve module file requests by looking for matching files with

但是大多数import语句完全不会去引用扩展名。 所以我们要告诉Webpack如何通过查找匹配的文件来解析模块文件的加载请求:

config/webpack.common.js

resolve: { extensions: ['', '.ts', '.js'] },

We could add .css and .html later if we want Webpack to resolve extension-less files with those extension too.

我们以后还可能会添加.css.html —— 如果希望Webpack也用无扩展名的方式去解析那些扩展名的话。

Next we specify the loaders:

接下来我们开始指定加载器:

config/webpack.common.js

module: { loaders: [ { test: /\.ts$/, loaders: ['awesome-typescript-loader', 'angular2-template-loader'] }, { test: /\.html$/, loader: 'html' }, { test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/, loader: 'file?name=assets/[name].[hash].[ext]' }, { test: /\.css$/, exclude: helpers.root('src', 'app'), loader: ExtractTextPlugin.extract('style', 'css?sourceMap') }, { test: /\.css$/, include: helpers.root('src', 'app'), loader: 'raw' } ] },

The first pattern excludes .css files within the /src/app directories where our component-scoped styles sit. It includes only .css files located at or above /src; these are the application-wide styles. The ExtractTextPlugin (described below) applies the style and css loaders to these files.

第一个模式排除了/src/app目录下的.css文件,因为那里放着我们的组件局部样式。 它只包含了那些位于/src及其上级目录的.css文件,那里是应用级样式。 ExtractTextPlugin(后面会讲到)使用stylecss加载器来处理这些文件。

The second pattern filters for component-scoped styles and loads them as strings via the raw loader — which is what Angular expects to do with styles specified in a styleUrls metadata property.

第二个模式过滤器是给组件局部样式的,并通过raw加载器把它们加载成字符串 —— 那是Angular期望通过元数据的styleUrls属性来指定样式的形式。

Multiple loaders can be also chained using the array notation.

多重加载器也能使用数组形式串联起来。

Finally we add two plugins:

最后我们来添加两个插件:

config/webpack.common.js

plugins: [ new webpack.optimize.CommonsChunkPlugin({ name: ['app', 'vendor', 'polyfills'] }), new HtmlWebpackPlugin({ template: 'src/index.html' }) ]

CommonsChunkPlugin

We want the app.js bundle to contain only app code and the vendor.js bundle to contain only the vendor code.

我们希望app.js包中只包含应用代码,而vendor.js包中只包含提供商代码。

Our application code imports vendor code. Webpack is not smart enough to keep the vendor code out of the app.js bundle. We rely on the CommonsChunkPlugin to do that job.

应用代码中import了提供商代码。Webpack还没有智能到自动把提供商代码排除在app.js包之外。 CommonsChunkPlugin插件能完成此工作。

It identifies the hierarchy among three chunks: app -> vendor -> polyfills. Where Webpack finds that app has shared dependencies with vendor, it removes them from app. It would do the same if vendor and polyfills had shared dependencies (which they don't).

这里标记出了三个之间的等级体系:app -> vendor -> polyfills。 当Webpack发现appvendor有共享依赖时,就把它们从app中移除。 在vendorpolyfills之间有共享依赖时也同样如此(虽然它们没啥可共享的)。

HtmlWebpackPlugin

Webpack generates a number of js and css files. We could insert them into our index.html manually. That would be tedious and error-prone. Webpack can inject those scripts and links for us with the HtmlWebpackPlugin.

Webpack生成了一些js和css文件。 虽然我们可以手动把它们插入到index.html中,但那样既枯燥又容易出错。 Webpack可以通过HtmlWebpackPlugin自动为我们注入那些scriptlink标签。

Environment-specific configuration

环境相关的配置

The webpack.common.js configuration file does most of the heavy lifting. We create separate, environment-specific configuration files that build on webpack.common by merging into it the peculiarities particular to their target environments.

webpack.common.js配置做了大部分繁重的工作。 通过合并它们特有的配置,我们可以基于webpack.common为目标环境创建独立的、环境相关的配置文件。

These files tend to be short and simple.

这些文件越小越简单越好。

Development Configuration

开发环境配置

Here is the development configuration file, webpack.dev.js

下面是开发环境的而配置文件webpack.dev.js

config/webpack.dev.js

var webpackMerge = require('webpack-merge'); var ExtractTextPlugin = require('extract-text-webpack-plugin'); var commonConfig = require('./webpack.common.js'); var helpers = require('./helpers'); module.exports = webpackMerge(commonConfig, { devtool: 'cheap-module-eval-source-map', output: { path: helpers.root('dist'), publicPath: 'http://localhost:8080/', filename: '[name].js', chunkFilename: '[id].chunk.js' }, plugins: [ new ExtractTextPlugin('[name].css') ], devServer: { historyApiFallback: true, stats: 'minimal' } });

The development build relies on the Webpack development server which we configure near the bottom of the file.

开发环境下的构建依赖于Webpack的开发服务器,我们在靠近文件底部的地方配置了它。

Although we tell Webpack to put output bundles in the dist folder, the dev server keeps all bundles in memory; it doesn't write them to disk. So we won't find any files in the dist folder (at least not any generated from this development build).

虽然我们告诉Webpack把输出包放到dist目录,但实际上开发服务器把这些包都放在了内存里,而不会把它们写到硬盘中。 所以在dist目录下是找不到任何文件的(至少现在这个开发环境下构建时没有)。

The HtmlWebpackPlugin (added in webpack.common.js) use the publicPath and the filename settings to generate appropriate <script> and <link> tags into the index.html.

HtmlWebpackPlugin(由webpack.common.js引入)插件使用了publicPathfilename设置, 来向index.html中插入适当的<script>和<link>标签。

Our CSS are buried inside our Javascript bundles by default. The ExtractTextPlugin extracts them into external .css files that the HtmlWebpackPlugin inscribes as <link> tags into the index.html.

我们这些CSS默认情况下会被埋没在JavaScript包中。ExtractTextPlugin会把它们提取成外部.css文件, 这样HtmlWebpackPlugin插件就会转而把一个<link>标签写进index.html了。

Refer to the Webpack documentation for details on these and other configuration options in this file

要了解本文件中这些以及其它配置项的详情,请参阅Webpack文档。

Grab the app code at the end of this guide and try:

抓取本指南底部的应用代码,并试一试:

npm start

Production Configuration

产品环境配置

Configuration of a production build resembles development configuration ... with a few key changes.

产品环境下的配置和开发环境下的配置很相似……除了一些关键的改动。

config/webpack.prod.js

var webpack = require('webpack'); var webpackMerge = require('webpack-merge'); var ExtractTextPlugin = require('extract-text-webpack-plugin'); var commonConfig = require('./webpack.common.js'); var helpers = require('./helpers'); const ENV = process.env.NODE_ENV = process.env.ENV = 'production'; module.exports = webpackMerge(commonConfig, { devtool: 'source-map', output: { path: helpers.root('dist'), publicPath: '/', filename: '[name].[hash].js', chunkFilename: '[id].[hash].chunk.js' }, htmlLoader: { minimize: false // workaround for ng2 }, plugins: [ new webpack.NoErrorsPlugin(), new webpack.optimize.DedupePlugin(), new webpack.optimize.UglifyJsPlugin({ // https://github.com/angular/angular/issues/10618 mangle: { keep_fnames: true } }), new ExtractTextPlugin('[name].[hash].css'), new webpack.DefinePlugin({ 'process.env': { 'ENV': JSON.stringify(ENV) } }) ] });

We don't use a development server. We're expected to deploy the application and its dependencies to a real production server.

我们不会在产品环境下使用开发服务器,而是希望把应用程序及其依赖都部署到一个真实的产品服务器中。

This time the output bundle files are physically placed in the dist folder.

这次,输出的包文件就被真的放到dist目录下了。

Webpack generates file names with cache-busting hash. Thanks to the HtmlWebpackPlugin we don't have to update the index.html file when the hashes changes.

Webpack生成的文件名中带有“缓存无效哈希(cache-busting hash)”。 感谢HtmlWebpackPlugin插件,当这些哈希值变化时,我们不用去更新index.html了。

There are additional plugins:

还有一些别的插件:

Thanks to the DefinePlugin and the ENV variable defined at top, we can enable Angular production mode like this:

感谢DefinePlugin和顶部定义的ENV变量,我们就可以像这样启用Angular的产品模式了:

if (process.env.ENV === 'production') { enableProdMode(); }

Grab the app code at the end of this guide and try:

抓取本指南底部的应用代码,并试一试:

npm run build

Test Configuration

测试环境配置

We don't need much configuration to run unit tests. We don't need the loaders and plugins that we declared for our development and production builds. We probably don't need to load and process the application-wide styles files for unit tests and doing so would slow us down; we'll use the null loader for those CSS.

我们并不需要使用很多配置项来运行单元测试。 也不需要在开发环境和产品环境下引入的那些加载器和插件。 如果有可能拖慢执行速度,甚至都不需要在单元测试中加载和处理应用全局样式文件,所以我们用一个null加载器来处理所有CSS。

We could merge our test configuration into the webpack.common configuration and override the parts we don't want or need. But it might be simpler to start over with a completely fresh configuration.

我们可以把测试环境的配置合并到webpack.common配置中,并且改写不想要或不需要的部分。 但是从一个全新的配置开始可能更简单。

config/webpack.test.js

var helpers = require('./helpers'); module.exports = { devtool: 'inline-source-map', resolve: { extensions: ['', '.ts', '.js'] }, module: { loaders: [ { test: /\.ts$/, loaders: ['awesome-typescript-loader', 'angular2-template-loader'] }, { test: /\.html$/, loader: 'html' }, { test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/, loader: 'null' }, { test: /\.css$/, exclude: helpers.root('src', 'app'), loader: 'null' }, { test: /\.css$/, include: helpers.root('src', 'app'), loader: 'raw' } ] } }

Here's our karma configuration:

这里是我们的Karma配置:

config/karma.conf.js

var webpackConfig = require('./webpack.test'); module.exports = function (config) { var _config = { basePath: '', frameworks: ['jasmine'], files: [ {pattern: './config/karma-test-shim.js', watched: false} ], preprocessors: { './config/karma-test-shim.js': ['webpack', 'sourcemap'] }, webpack: webpackConfig, webpackMiddleware: { stats: 'errors-only' }, webpackServer: { noInfo: true }, reporters: ['progress'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: false, browsers: ['PhantomJS'], singleRun: true }; config.set(_config); };

We're telling Karma to use webpack to run the tests.

我们告诉Karma使用Webpack来运行测试。

We don't precompile our TypeScript; Webpack transpiles our Typescript files on the fly, in memory, and feeds the emitted JS directly to Karma. There are no temporary files on disk.

我们不用预编译TypeScript,Webpack随时在内存中转译我们的TypeScript文件,并且把产出的JS直接反馈给Karma。 硬盘上没有任何临时文件。

The karma-test-shim tells Karma what files to pre-load and primes the Angular test framework with test versions of the providers that every app expects to be pre-loaded.

karma-test-shim告诉Karma哪些文件需要预加载,首要的是:带有“测试版提供商”的Angular测试框架是每个应用都希望预加载的。

config/karma-test-shim.js

Error.stackTraceLimit = Infinity; require('core-js/es6'); require('core-js/es7/reflect'); require('zone.js/dist/zone'); require('zone.js/dist/long-stack-trace-zone'); require('zone.js/dist/proxy'); require('zone.js/dist/sync-test'); require('zone.js/dist/jasmine-patch'); require('zone.js/dist/async-test'); require('zone.js/dist/fake-async-test'); var appContext = require.context('../src', true, /\.spec\.ts/); appContext.keys().forEach(appContext); var testing = require('@angular/core/testing'); var browser = require('@angular/platform-browser-dynamic/testing'); testing.TestBed.initTestEnvironment(browser.BrowserDynamicTestingModule, browser.platformBrowserDynamicTesting());

Notice that we do not load our application code explicitly. We tell Webpack to find and load our test files (the files ending in .spec.ts). Each spec file imports all — and only — the application source code that it tests. Webpack loads just those specific application files and ignores the other files that we aren't testing.

注意,我们并没有明确加载这些应用代码。 只是告诉Webpack查找并加载我们的测试文件(文件名以.spec.ts结尾)。 每个规约(spec)文件都导入了所有(也只有)它测试所需的应用源码。 Webpack只加载那些特定的应用文件,而忽略所有其它我们不会测试到的。

Grab the app code at the end of this guide and try:

抓取本指南底部的应用代码,并试一试:

npm test

Trying it out

试一试

Here is the source code for a small application that we can bundle with the Webpack techniques we learned in this chapter.

这里是一个小型应用的全部源码,我们可以用本章中学到的Webpack技术打包它们。

<!DOCTYPE html> <html> <head> <base href="/"> <title>Angular With Webpack</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <my-app>Loading...</my-app> </body> </html> import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { enableProdMode } from '@angular/core'; import { AppModule } from './app/app.module'; if (process.env.ENV === 'production') { enableProdMode(); } platformBrowserDynamic().bootstrapModule(AppModule); body { background: #0147A7; color: #fff; } 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 { } <main> <h1>Hello from Angular App with Webpack</h1> <img src="../../public/images/angular.png"> </main> main { padding: 1em; font-family: Arial, Helvetica, sans-serif; text-align: center; margin-top: 50px; display: block; } import { TestBed } from '@angular/core/testing'; import { AppComponent } from './app.component'; describe('App', () => { beforeEach(() => { TestBed.configureTestingModule({ declarations: [AppComponent]}); }); it ('should work', () => { let fixture = TestBed.createComponent(AppComponent); expect(fixture.componentInstance instanceof AppComponent).toBe(true, 'should create AppComponent'); }); }); import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; @NgModule({ imports: [ BrowserModule ], declarations: [ AppComponent ], bootstrap: [ AppComponent ] }) export class AppModule { }

The app.component.html displays this downloadable Angular logo .

app.component.html显示了这个可下载的Angular Logo

// Angular import '@angular/platform-browser'; import '@angular/platform-browser-dynamic'; import '@angular/core'; import '@angular/common'; import '@angular/http'; import '@angular/router'; // RxJS import 'rxjs'; // Other vendors for example jQuery, Lodash or Bootstrap // You can import js, ts, css, sass, ... import 'core-js/es6'; import 'core-js/es7/reflect'; require('zone.js/dist/zone'); if (process.env.ENV === 'production') { // Production } else { // Development Error['stackTraceLimit'] = Infinity; require('zone.js/dist/long-stack-trace-zone'); }

Highlights:

重点:

Conclusions

总结

We've learned just enough Webpack to configurate development, test and production builds for a small Angular application.

我们学到了刚好够用来在开发、测试、产品环境下构建一个小型Angular应用的Webpack配置知识。

We could always do more. Search the web for expert advice and expand your Webpack knowledge.

但我们还能做得更多。搜索互联网来获得专家的建议,并扩展你对Webpack的认识。

Back to top

回到顶部