原文:https://commandlinefanatic.com/cgi-bin/showarticle.cgi?article=art074

-------------------------------------------------------

Angular CLI behind the scenes, part one

Google's Angular is a fairly popular web application development framework - although it has some competition from Facebook's React, there still seems to be quite a bit of support for it out there. Angular is on its 6th iteration now; one complaint that earlier versions got was around the amount of "boilerplate" code that you had to write to get even a simple application up and running. As of today, the preferred solution to this problem is a command-line application generator (rather than, say, a GUI wizard-based approach) called the Angular CLI. This is fine in the sense that it works, but it does quite a bit behind the scenes and expends a lot of effort hiding the details of what it did from you, the developer. On the one hand, this is helpful for beginners because everything "just works". On the other hand, this is a problem once you leave the beginner stage because any automation, by its nature, has to make a fair number of assumptions on your behalf. If you're not aware of what those assumptions are, you can end up tripping headlong over one or more of them with a completely inexplicable error. In this post, I'm going to walk through the Tour of Heroes tutorial and peel back a bit of the mystery behind the "magical" commands.

Step 1: Install the Angular CLI

Although, strictly speaking, Angular doesn't actually require Node.js, the recommended Angular workflow leans pretty heavily on Node and NPM. Node is a Javascript environment that can be run from the command line and NPM is its package manager. The first thing that the Angular Tour of Heroes tutorial asks you to do is to use Node's NPM to install the Angular CLI "globally":

npm install -g @angular/cli

If you run this without the -g (global) flag, it will do the following:

  1. Connect to (by default) the central NodeJS registry at https://registry.npmjs.org, look for the path @angular/cli and download the descriptor. If you click through, you can see that it's a very long JSON file that describes what Javascript files make up the Angular CLI and the other packages that the Angular CLI depends on. There are quite a few.
  2. Parse and process the package descriptor. One of the more important entries in the descriptor is the entry dist/tarball, which is where NPM finds the actual contents of the package.
  3. Create a directory named node_modules underneath the current directory. The Javascript code that makes up the Angular CLI, along with all of its dependencies, and their dependencies, is downloaded into it. There are quite a few dependencies: 193 packages, containing 6,515 files, at the time of this writing.

However, the tutorial instructs you to run it with the -g flag instead. If you do as it instructs, you see that a lot happens, but nothing changes in the current directory. Even stranger, although nothing has changed, the next thing that the tutorial instructs you to do is to run the command:

ng new my-app

which, if you run it, does work. If you have a useful terminal that supports a command like which, you can see where this mysterious new ng command came from:

$ which ng
/home/jdavies/.nvm/versions/node/v10.9.0/bin/ng

If you have a less useful terminal, though, you can still piece together what happened; when you install an NPM package "globally", it adds the binary contents of the package, as described by the package descriptors bin entry, underneath the bin directory of your NPM prefix:

C:\test\angular> npm config get prefix
C:\Users\jodavies.NA\AppData\Roaming\npm

If you take a peek in there, you see that everything that would have happened had you installed the Angular CLI locally was done in this centralized directory. You can see that it's not structured quite the same as a "local" install; the Angular CLI binary is installed under prefix/lib/node_modules, but it's dependencies are installed under prefix/lib/node_modules/@angular/cli/node_modules. The differences, though, are minimal, and the command-line tools keep track of them.

If you paid attention to the output of the original install invocation, it reported the location of this directory there, as well.

If for some reason, you don't want to install ng globally and have it appear in your system path, the local installation adds the executable script under node_modules/.bin — you can effectively run it from there, but you'll have to either add that directory to your path or give the relative path from the command line each time you invoke it.

Step 2: Generate the base application

So, ng new is a new command-line tool, now globally available (npm prefix/bin is in your $PATH environment variable). ng is either a shell script whose first line is:

#!/usr/bin/env node

Or a .cmd that invokes node with the CLI Javascript input. It's worth noting that you should only have to npm install @angular/cli one time — in fact, subsequent invocations might actually upgrade the global copy, which could conceivably cause a build that used to work to inexplicably break.

ng new, then, creates a new Angular app. Unsurprisingly, this goes into a new directory of the same name as the third parameter; my-app in the case of the Angular tutorial. You can see from the output that it's following a script — so, where does the Angular CLI go to find this script to figure out what to create? If you poke around the source code a bit, you can find these instructions in node_modules/@angular-devkit/schematics, which was downloaded when you installed the CLI. As you can see, this does quite a bit - it creates some boilerplate code and downloads 792 (!) packages consisting of 31,728 (!!) files.

Step 3: Run the application

Now, the Angular tutorial instructs you to run ng serve --open. If you leave off the --open option for a moment and just run ng serve, the Angular CLI utility ng will start up a web server on port 4200. If you navigate to it in a browser, you'll see the "Welcome to my-app" hello world template. If you go back and take a look at the generated code, you can see that there's an index.html file and, if you compare the source of the landing page against src/index.html, they're close to one another, but not identical: what shows up in the browser has a few additional script tags toward the bottom. Where did these come from?

Well, ng serve isn't just a static web server, but an Angular-aware web server that also builds the code for you in memory, invisibly, before serving it up. If you want to get a better idea of what ng serve is doing behind the scenes, you can invoke ng build to see the interim product. (In fact, it's not called out specifically by the tutorial itself, but if you want to run this code on any server except the test ng serve server, you have to do this and deploy the results). Doing so creates a dist directory that includes all of the source code that is required to run the app. The only difference between the auto-generated index.html source and the built target is the inclusion of five new Javascript files:

  • runtime.js
  • polyfills.js
  • styles.js
  • vendor.js
  • main.js

So, what are these, and how did ng build (or ng serve) know where to find them/generate them and insert them?

As it turns out, ng build is a wrapper over the webpack library/utility. Webpack, itself, is a modularization/ build framework for Javascript applications. "Build framework for Javascript" feels like a misnomer to older Javascript developers — Javascript is executable as-is (in fact, that's the only way it's executable), so the need to "build" anything seems out of place. But in reality, any moderately complex web application will consist of enough interleaved Javascript files that, at the very least, bundling all of them together and minifying them into a single download will provide significant runtime performance benefits. Beyond that, though, it's common to rely on third-party Javascript libraries (maybe a little too common), so the deployment process typically involves bundling additional libraries not under the developer's control along with the application's code. If those dependencies have their own dependencies, you run into dependency resolution issues (i.e. I'm using jQuery 1.7 and you're using 1.8 — which one do we include at runtime?) Webpack follows a configuration file named webpack.config.js and uses that do resolve modules, handle CJS/AMD/ES6 conflicts, and bundle up the whole thing into something that a browser can run.

There's more to webpack, in fact — asynchronous or just-in-time module loading, tree-shaking (removing unused functions), and hot module reloading, for example.

So, webpack is responsible for encapsulating, compressing, bundling, etc. the source code files, but still — how does ng build tell it where and what to process? There's no webpack.config.js file to be found, after all, and it's obviously not following the defaults. Instead, the file angular.json (which used to be a "hidden" file named .angular-cli.json in earlier Angular releases) includes this instruction along with quite a few others. In earlier versions of Angular, you could run ng eject to see the implied webpack.config.js and, if necessary, tweak it — you can't do this any more, but this functionality was of dubious value since the resulting configuration file ran into the hundreds of lines.

Although the configuration options of the angular.json file are pretty sparsely documented, it's not hard to figure out what it's doing. The relevant section appears toward the beginning of the file:

"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/my-app",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "src/tsconfig.app.json",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.css"
],
"scripts": []
},

You can mentally map most of that back to the scripts that were inserted to index.html (itself identified by the index entry) — polyfills transpiled into polyfills.js and main transpiled into main.ts. The styles entry instructs the Webpack CSS loader to generate the styles.js javascript file that compresses and encapsulates CSS — you may notice that there are no CSS imports in the generated application!

You probably know that polyfills is a standard add-in that allows you to run Angular apps in older browsers (and if you didn't know that, you know it now), which you'll probably never touch except to uncomment some lines if you want IE support, and that main.ts is the actual startup file for Angular (which you also probably won't spend much time with - you'll start with app.module.ts instead). That leaves runtime.js and vendor.js unaccounted for.

To make more sense of these (as well as the contents of the other three), you need a firm grounding in Javascript modules or rather, the lack thereof. Since Javascript was originally conceived as a scripting add-on for web pages, and web pages themselves were originally pretty small and limited in functionality, there wasn't much attention paid to larger software engineering concepts like modularity in its early stages. The original Javascript had two effective variable scopes: global and function-level. This was OK early on — a globally-scoped variable was only scoped globally to the page it was contained in, and early web applications consisted of dozens of individual pages. In fact, sharing data across pages was a bigger problem in early Javascript applications than modular information hiding — 90's Javascript developers spent a lot of time juggling cookies to create consistency across multiple pages.

With the rise and popularity of Ajax-driven singe-page applications, though, the necessity of an intermediate "module" scope — somewhere in between global and local — became apparent. Since Javascript didn't support it, though, clever developers started faking it by wrapping their conceptual modules inside functions. Although ES6 does have a syntax for declaring modules, there's a lot of this modules-in-functions workaround-ery still to be found, and webpack still treats it as a first-class citizen. So, if you look at the first Javascript file that's loaded at runtime (appropriately named runtime.js), it's a single Immediately Invoked Functional Expression (IIFE) that accepts a parameter named modules. This configures the webpack modular system which the remaining files rely on.

Back to the original ng serve --open, though: if you do include the instructed --open parameter, ng goes ahead and opens a browser for you and navigates to the landing page of the newly minted application. It doesn't just open up a browser, though — if you modify the source code of the application, it will automatically reload the application in the browser. How is this magic accomplished? I'll go into that, along with adding new Angular components, in the next part of this series.

Angular CLI behind the scenes, part one的更多相关文章

  1. Configure a proxy for your API calls with Angular CLI

    Table of contents Local development setup with Angular Issue: Dev server plus backend API Configurin ...

  2. Angular环境准备和Angular cli

    Angular4.0来了,更小,更快,改动少 接下来为Angular4.0准备环境和学会使用Angular cli项目 1.环境准备: 1)在开始工作之前我们必须设置好开发环境 如果你的机器上还没有安 ...

  3. 迈向angularjs2系列(8):angular cli和angular2种子项目

    文章目录 1.angular cli快速搭建项目 2.angular2-seed 3.手动配置 题外话:如何更好的阅读本篇文章 一: angular cli的安装 Angular-cli(命令行界面, ...

  4. Visual Studio Code作为Angular开发工具常用插件安装、json-server安装与使用、angular/cli安装失败问题

    前提准备: 搭建好Angular开发环境 1 安装Visual Studio Code 教程简单,不会的去问度娘 2 安装Chrome浏览器 教程简单,不会的趣闻度娘 3 Visual Studio ...

  5. angular4.0 安装最新版本的nodejs、npm、@angular/cli的方法

    在使用ng项目的ui框架时,比如ng-zorro.angular Material,需要安装最新版本的@angular/cli: 配置ng-zorro框架 ng-zorro官网:https://ng. ...

  6. 使用Angular CLI生成 Angular 5项目

    如果您正在使用angular, 但是没有好好利用angular cli的话, 那么可以看看本文. Angular CLI 官网: https://github.com/angular/angular- ...

  7. Angular4---起步----环境配置安装@angular/cli

    学习angular,首先要搭建起angular的手脚架@angular/cli.首先需要NodeJS环境. 1.安装NodeJS 首先检查电脑是否安装了NodeJS环境,打开cmd命令行,运行node ...

  8. 使用Angular CLI进行单元测试和E2E测试

    第一篇文章是: "使用angular cli生成angular5项目" : http://www.cnblogs.com/cgzl/p/8594571.html 第二篇文章是: & ...

  9. 使用Angular CLI从蓝本生成代码

    第一篇文章是: "使用angular cli生成angular5项目" : http://www.cnblogs.com/cgzl/p/8594571.html 这篇文章主要是讲生 ...

随机推荐

  1. Tomcat免安装版执行tomcat9.exe闪退

    Tomcat免安装版点击startup.bat可成功启动,但是执行tomcat9.exe时却闪退,这是因为免安装版的tomcat不会自动把tomcat注册到windows服务里,需要手动注册. 解决办 ...

  2. RAID磁盘阵列结构

    RAID磁盘阵列结构原理其实很简单,就是每块硬盘不插在主板的硬盘接口上了,而是全插在RAID卡上,然后RAID卡再插到主板上,由RAID卡统一管理硬盘,做各种RAID磁盘策略(RAID0,RAID1, ...

  3. javadoc 抽出代码中的注释

    背景: 在已经有的项目里面利用javadoc来抽出代码中每个类,每个方法的注释部分,形成一个文档. 方法1 利用eslipse来实现 之后会在指定的目录下生成html文档 方法2 利用命令来执行 先把 ...

  4. java-统计一段句子中各单词出现的次数

    问题:统计一段句子中各单词出现的次数. 思路: 1.使用split方法将文章进行分割,我们这里以空格.逗号和句点为分隔符,然后存到一个字符串数组中. 2.创建一个hashMap集合,key是字符串类型 ...

  5. 谈谈php里的IOC控制反转,DI依赖注入(转)

    转自:http://www.cnblogs.com/qq120848369/p/6129483.html 发现问题 在深入细节之前,需要确保我们理解"IOC控制反转"和" ...

  6. [转帖]WannaCry惊天大发现!疑似朝鲜黑客组织Lazarus所为

    WannaCry惊天大发现!疑似朝鲜黑客组织Lazarus所为 Threatbook2017-05-16共588524人围观 ,发现 17 个不明物体系统安全 https://www.freebuf. ...

  7. Java基础笔试练习(九)

    1.下面所示的java代码,运行时,会产生()类型的异常 ? int Arry_a[] = new int[10]; System.out.println(Arry_a[10]); A.Arithme ...

  8. Ubuntu19.04 Help

    Ubuntu Dock 为应用程序启用最小化操作,立即生效. $ gsettings set org.gnome.shell.extensions.dash-to-dock click-action ...

  9. 深度学习-语言处理特征提取 Word2Vec笔记

    Word2Vec的主要目的适用于词的特征提取,然后我们就可以用LSTM等神经网络对这些特征进行训练. 由于机器学习无法直接对文本信息进行有效的处理,机器学习只对数字,向量,多维数组敏感,所以在进行文本 ...

  10. HuTool之判断上传文件的文件类型

    文件类型判断-FileTypeUtil 由来 在文件上传时,有时候我们需要判断文件类型.但是又不能简单的通过扩展名来判断(防止恶意脚本等通过上传到服务器上),于是我们需要在服务端通过读取文件的首部几个 ...