Angular CLI - Tutorials Point

Transcription

Angular CLIi

Angular CLIAbout the TutorialAngular CLI makes it easy to start with any Angular project. Angular CLI comes withcommands that help us create and start on our project very fast. It has commands tocreate a project, a component and services, change the port, etc.AudienceThis tutorial is designed for software programmers who want to learn the basics of AngularCLI and its concepts in a simple and easy manner. This tutorial will give you enoughunderstanding on the various functionalities of Angular CLI with suitable examples.PrerequisitesBefore proceeding with this tutorial, you should have a basic understanding of HTML, CSS,JavaScript, Typescript, and Document Object Model (DOM).Copyright & Disclaimer Copyright 2020 by Tutorials Point (I) Pvt. Ltd.All the content and graphics published in this e-book are the property of Tutorials Point (I)Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republishany contents or a part of contents of this e-book in any manner without written consentof the publisher.We strive to update the contents of our website and tutorials as timely and as precisely aspossible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt.Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of ourwebsite or its contents including this tutorial. If you discover any errors on our website orin this tutorial, please notify us at contact@tutorialspoint.comi

Angular CLITable of ContentsAbout the Tutorial . iAudience . iPrerequisites . iCopyright & Disclaimer . iTable of Contents . ii1.Angular CLI – Overview . 1Commands for Angular 4 . 12.Angular CLI — Environment Setup . 3Download Node.js archive . 3Installation on UNIX/Linux/Mac OS X, and SunOS. 3Installation on Windows . 43.Angular CLI — ng version Command . 64.Angular CLI — ng new Command . 85.Angular CLI — ng help Command . 136.Angular CLI — ng generate Command . 187.Angular CLI — ng build Command . 208.Angular CLI — ng run Command . 269.Angular CLI — ng serve Command . 2810. Angular CLI — ng lint Command . 3211. Angular CLI — ng test Command . 3612. Angular CLI — ng e2e Command . 4113. Angular CLI — ng add Command . 4514. Angular CLI — ng analytics Command . 4715. Angular CLI — ng config Command . 4916. Angular CLI — ng doc Command . 5117. Angular CLI — ng update Command . 53ii

Angular CLI18. Angular CLI — ng xi18n Command . 5519. Angular CLI — Code Coverage . 58iii

1. Angular CLI – OverviewAngular CLIAngular command-line interface (CLI) makes it easy to start with any Angular project. Itcomes with commands that help us create and start on our project very fast. Let us nowgo through the commands available to create a project, a component and services, changethe port, etc.To work with Angular CLI, we need to have it installed on our system. Let us use thefollowing command for the same:npm install -g @angular/cliTo create a new project, we can run the following command in the command line and theproject will be created.ng new PROJECT-NAMEcd PROJECT-NAMEng serve //ng serve // will compile and you can see the output of your project in the browser:http://localhost:4200/4200 is the default port used when a new project is created. You can change the port withthe following command:ng serve --host 0.0.0.0 --port 4201Commands for Angular 4The following table lists down a few important commands which are required while workingwith the Angular 4 projects.Sr.No1Commands & DescriptionComponentng g component new-component2Directiveng g directive new-directive3Pipe1

Angular CLIng g pipe new-pipe4Serviceng g service new-service5Moduleng g module my-moduleWhenever a new module, a component, or a service is created, the reference of the sameis updated in the parent module app.module.ts.2

2. Angular CLI — Environment SetupAngular CLITo work with Angular CLI, we need to have Node installed on our system. Let usunderstand about the environment setup required for Angular CLI in detail.Download Node.js archiveDownload latest version of Node.js installable archive file from Node.js Downloads,which is available at https://nodejs.org/download/. At the time of writing this tutorial, theversions available on different OS are listed below:OSArchive node-v6.3.1-sunos-x86.tar.gzInstallation on UNIX/Linux/Mac OS X, and SunOSBased on your OS architecture, download and extract the archive node-v6.3.1osname.tar.gz into /tmp, and then, finally move extracted files into /usr/local/nodejsdirectory.For example: cd /tmp wget 4.tar.gz tar xvfz node-v6.3.1-linux-x64.tar.gz mkdir -p /usr/local/nodejs mv node-v6.3.1-linux-x64/* /usr/local/nodejsAdd /usr/local/nodejs/bin to the PATH environment variable.OSLinuxOutputexport PATH PATH:/usr/local/nodejs/bin3

Angular CLIMacexport PATH PATH:/usr/local/nodejs/binFreeBSDexport PATH PATH:/usr/local/nodejs/binInstallation on WindowsUse the MSI file and follow the prompts to install the Node.js. By default, the installeruses the Node.js distribution in C:\Program Files\nodejs.The installer should set the C:\Program Files\nodejs\bin directory in windows PATHenvironment variable. Restart any open command prompts for the change to take effect.Verify installation: Executing a FileCreate a js file named main.js on your machine (Windows or Linux) having the followingcode:/* Hello, World! program in node.js */console.log("Hello, World!")The link for live demo is https://www.tutorialspoint.com/execute nodejs online.php.Now, execute main.js file using Node.js interpreter to see the result: node main.jsIf everything is fine with your installation, this should produce the following result:Hello, World!Now, the Node is installed. You can run the following command to install Angular CLI.npm install -g @angular/cliVerify the installationNow, run the following command to see the result: ng --versionIf everything is fine with your installation, this should produce the following result:/ \ / ? \ ' \ / / ' / \ ( ( / /\ \ \ , \ , \ , // \ 4

Angular CLIAngular CLI: 9.1.0Node: 12.16.1OS: win32 x64Angular:.Ivy /update0.901.0rxjs6.5.4On Windows, in case of ng being not recognised as internal or external command, updatethe system path variable to include the following path.C:\Users\ User Directory \AppData\Roaming\npm5

3. Angular CLI — ng version CommandAngular CLIThis chapter explains the syntax, options of ng version command along with an example.SyntaxThe syntax for ng version command is as follows:ng version [options]ng v [options]ng version command shows the Angular CLI version installed.OptionsOptions are optional parameters.Sr.No.Option & Syntax1Description--help Shows a help message for this command in the console.true false json JSONDefault: falseExampleAn example for ng version command is given below:\ Node ng version/ \ / ? \ ' \ / / ' / \ ( ( / /\ \ \ , \ , \ , / \ /Angular CLI: 9.1.0Node: 12.16.16

Angular CLIOS: win32 x64Angular:.Ivy /update0.901.0rxjs6.5.47

4. Angular CLI — ng new CommandAngular CLIThis chapter explains the syntax, argument and options of ng new command along withan example.SyntaxThe syntax for ng new command is as follows:ng new name [options]ng n name [options]ng new command creates a workspace of given name with a default Angular Application.It provides interactive prompts to set optional configurations. All prompts have defaultvalues to choose.ArgumentThe argument for ng new command is as follows:Sr.No.1Argument & Syntax name DescriptionThe name of the new workspace and initial project.OptionsOptions are optional parameters.Sr.No.1Option & Syntax--collection collectionDescriptionA collection of schematicsto use in generating theinitial app.Aliases: -c.2--commit true falseInitialgitrepositorycommit information.Default: true.3--createApplication true falseWhen true (the default),creates a new initial appproject in the src folder ofthe new workspace. Whenfalse, creates an empty8

Angular CLIworkspace with no initialapp. You can then use togenerateapplicationcommand so that all appsare created in the projectsfolder.Default: true.4--defaults true falseWhentrue,disablesinteractive input promptsfor options with a default.5--directory directoryThe directory name tocreate the workspace in.6--dryRun true falseWhen true, runs Default: false.Aliases: -d.7--force true falseWhentrue,overwriting offiles.forcesexistingDefault: false.Aliases: -f.8--help true false json JSONShows a help message forthis command in theconsole.Default: false.9--inlineStyle true falseWhen true, includes stylesinline in the componentTS file. By default, anexternal styles file iscreated and referenced inthe component TS file.Default: false.10--inlineStyle true falseWhen true, includes stylesinline in the component9

Angular CLITS file. By default, anexternal styles file iscreated and referenced inthe component TS file.Default: false.Aliases: -t.11--interactive true falseWhenfalse,disablesinteractive input prompts.12--minimal true falseWhen true, creates aprojectwithoutanytesting frameworks. (Useforlearningpurposesonly.)Default: false.13--newProjectRoot newProjectRootThe path where newprojects will be created,relativetothenewworkspace root.Default: projects.14--packageManager npm yarn pnpm cnpmThe packageusedtodependencies.15--prefix prefixThe prefix to apply togenerated selectors forthe initial project.managerinstallDefault: app.Aliases: -p.16--routing true falseWhen true, generates arouting module for theinitial project.17--skipGit true falseWhen true, does notinitialize a git repository.Default: false.Aliases: -g.10

Angular CLI18--skipInstall true falseWhen true, does notinstalldependencypackages.Default: false.19--skipTests true falseWhen true, does notgenerate "spec.ts" testfiles for the new project.Default: false.Aliases: -S.20--strict true falseCreates a workspace withstricterTypeScriptcompiler options.Default: false.21--style css scss sass less stylThe file extension orpreprocessor to use forstyle files.22--verbose true falseWhen true, adds moredetails to output logging.Default: false.Aliases: -v.23-viewEncapsulation Emulated Native None ShadowDomThe view encapsulationstrategy to use in theinitial project.ExampleAn example for ng new command is given below:\ Node ng new TutorialsPoint? Would you like to add Angular routing? Yes? Which stylesheet format would you like to use? CSSCREATE TutorialsPoint/angular.json (3630 bytes)CREATE TutorialsPoint/package.json (1291 bytes)CREATE TutorialsPoint/README.md (1031 bytes)CREATE TutorialsPoint/tsconfig.json (489 bytes)11

Angular CLICREATE TutorialsPoint/tslint.json (3125 bytes)CREATE TutorialsPoint/.editorconfig (274 bytes)CREATE TutorialsPoint/.gitignore (631 bytes)CREATE TutorialsPoint/browserslist (429 bytes)CREATE TutorialsPoint/karma.conf.js (1026 bytes)CREATE TutorialsPoint/tsconfig.app.json (210 bytes)CREATE TutorialsPoint/tsconfig.spec.json (270 bytes)CREATE TutorialsPoint/src/favicon.ico (948 bytes)CREATE TutorialsPoint/src/index.html (300 bytes)CREATE TutorialsPoint/src/main.ts (372 bytes)CREATE TutorialsPoint/src/polyfills.ts (2835 bytes)CREATE TutorialsPoint/src/styles.css (80 bytes)CREATE TutorialsPoint/src/test.ts (753 bytes)CREATE TutorialsPoint/src/assets/.gitkeep (0 bytes)CREATE s (51 bytes)CREATE TutorialsPoint/src/environments/environment.ts (662 bytes)CREATE TutorialsPoint/src/app/app-routing.module.ts (246 bytes)CREATE TutorialsPoint/src/app/app.module.ts (393 bytes)CREATE TutorialsPoint/src/app/app.component.html (25755 bytes)CREATE TutorialsPoint/src/app/app.component.spec.ts (1083 bytes)CREATE TutorialsPoint/src/app/app.component.ts (218 bytes)CREATE TutorialsPoint/src/app/app.component.css (0 bytes)CREATE TutorialsPoint/e2e/protractor.conf.js (808 bytes)CREATE TutorialsPoint/e2e/tsconfig.json (214 bytes)CREATE TutorialsPoint/e2e/src/app.e2e-spec.ts (647 bytes)CREATE TutorialsPoint/e2e/src/app.po.ts (301 bytes)Packages installed successfully.Here, ng new command has created an angular workspace and a project with nameTutorialsPoint in our Node directory.12

5. Angular CLI — ng help CommandAngular CLIThis chapter explains the syntax and options of ng help command along with an example.SyntaxAn example for ng help command is given below:ng help [options]ng help command lists the available commands with their short descriptions.OptionsOptions are optional parameters.Sr.No.1Option & SyntaxDescription--help Shows a help message for this command in the console.true false json JSONDefault: falseExample 1An example for ng help command is given below:\ Node ng helpAvailable Commands:add Adds support for an external library to your project.analytics Configures the gathering of Angular CLI usage metrics. ring.build (b) Compiles an Angular app into an output directory named dist/ at thegiven output path. Must be executed from within a workspace directory.deploy Invokes the deploy builder for a specified project or for the defaultproject in the workspace.config Retrieves or sets Angular configuration values in the angular.jsonfilefor the workspace.doc (d) Opens the official Angular documentation (angular.io) in a browser,an13

Angular CLId searches for a given keyword.e2e (e) Builds and serves an Angular app, then runs end-to-end tests usingProtractor.generate (g) Generates and/or modifies files based on a schematic.help Lists available commands and their short descriptions.lint (l) Runs linting tools on Angular app code in a given project folder.new (n) Creates a new workspace and an initial Angular app.run Runs an Architect target with an optional custom builder configurationdefined in your project.serve (s) Builds and serves your app, rebuilding on file changes.test (t) Runs unit tests in a project.update Updates your application and its dependencies. Seehttps://update.angular.io/version (v) Outputs Angular CLI version.xi18n (i18n-extract) Extracts i18n messages from source code.For more detailed help run "ng [command name] --help"In case of individual commands, use the --help or -h option with the command. First moveto an angular project created using ng new command and then run the command. thttps://www.tutorialspoint.com/angular cli/angular cli ng new.htm.Example 2An example is given below:\ Node\ TutorialsPoint ng serve --helpBuilds and serves your app, rebuilding on file changes.usage: ng serve project [options]arguments:projectThe name of the project to build. Can be an application or a library.options:--allowed-hosts14

Angular CLIWhitelist of hosts that are allowed to access the dev server.--aotBuild using Ahead of Time compilation.--base-hrefBase url for the application being built.--browser-targetTarget to serve.--build-event-log**EXPERIMENTAL** Output file path for Build Event Protocol events--common-chunkUse a separate bundle containing code used across multiple bundles.--configuration (-c)A named build target, as specified in the "configurations" section ofangular.json.Each named target is accompanied by a configuration of option defaults for that target.Setting this explicitly overrides the "--prod" flag--deploy-urlURL where files will be deployed.--disable-host-checkDon't verify connected clients are part of allowed hosts.--eval-source-mapOutput in-file eval sourcemaps.--helpShows a help message for this command in the console.--hmrEnable hot module replacement.--hmr-warningShow a warning when the --hmr option is enabled.--hostHost to listen on.--live-reloadWhether to reload the page on change, using live-reload.--open (-o)Opens the url in default browser.15

Angular CLI--optimizationEnables optimization of the build output.--pollEnable and define the file watching poll time period in milliseconds.--portPort to listen on.--prodShorthand for "--configuration production".When true, sets the build configuration to the production target.By default, the production target is set up in the workspaceconfiguration such that all builds make use of bundling, limited tree-shaking, and alsolimiteddead code elimination.--progressLog progress to the console while building.--proxy-configProxy configuration file.--public-hostThe URL that the browser client (or live-reload client, if enabled)should usee to connect to the development server. Use for a complex dev server setup,such as one with reverse proxies.--serve-pathThe pathname where the app will be served.--serve-path-default-warningShow a warning when deploy-url/base-href use unsupported serve pathvalues.--source-mapOutput sourcemaps.--sslServe using HTTPS.--ssl-certSSL certificate to use for serving HTTPS.--ssl-keySSL key to use for serving HTTPS.--vendor-chunk16

Angular CLIUse a separate bundle containing only vendor libraries.--vendor-source-mapResolve vendor packages sourcemaps.--verboseAdds more details to output logging.--watchRebuild on change.17

6. Angular CLI — ng generate CommandAngular CLIThis chapter explains the syntax, argument and options of ng generate command alongwith an example.SyntaxThe syntax for ng generate command is as follows:ng generate schematic [options]ng g schematic [options]ng generate command generates and/or modifies files based on a schematic.ArgumentThe argument for ng help command is as follows:Sr.No.1DescriptionArgument &Syntax schematic The schematic or collection:schematic to generate. This option cantake one of the following sub-commands: ceWorkerwebWorkerOptionsOptions are optional parameters.18

Angular CLISr.No.Option & SyntaxDescription1--defaults true falseWhen true, disables interactive input prompts for optionswith a default.2--dryRun true falseWhen true, runs through and reports activity withoutwriting out results.Default: false.Aliases: -d.3--force true falseWhen true, forces overwriting of existing files.Default: false.Aliases: -f.45-help true false json JSONShows a help message for this command in the console.--interactive true falseWhen false, disables interactive input prompts.Default: false.First move to an angular project created using ng new command and then run orialspoint.com/angular cli/angular cli ng new.htm.ExampleAn example for ng generate command is given below:\ Node\ TutorialsPoint ng generate component goalsCREATE src/app/goals/goals.component.html (20 bytes)CREATE src/app/goals/goals.component.spec.ts (621 bytes)CREATE src/app/goals/goals.component.ts (271 bytes)CREATE src/app/goals/goals.component.css (0 bytes)UPDATE src/app/app.module.ts (471 bytes)Here, ng generate command has created a new component in our project TutorialsPointand added this new component entry in app.module.ts.19

7. Angular CLI — ng build CommandAngular CLIThis chapter explains the syntax, argument and options of ng build command along withan example.SyntaxThe syntax for ng build command is as follows:ng build project [options]ng b project [options]ng build command compiles an angular application/library into an output directory nameddist at given path.ArgumentsThe argument for ng build command is as follows:Sr.No.1Argument & Syntax project DescriptionThe name of the application or library to be built.OptionsOptions are optional parameters.Sr.No.1Option & Syntax--aot true falseDescriptionBuild using Ahead of Time compilation.Default: false.2--baseHref baseHrefBase url for the application being built.3--buildEventLog buildEventLogEXPERIMENTAL Output file path forBuild Event Protocol events.4--buildOptimizer true falseEnables'@angular-devkit/buildoptimizer' optimizations when usingthe 'aot' option.Default: false.20

Angular CLI5--commonChunk true falseUse a separate bundle containing codeused across multiple bundles.Default: false.6--configuration configurationA named build target, as specified inthe"configurations"sectionofangular.json. Each named target isaccompanied by a configuration ofoption defaults for that target. Settingthis explicitly overrides the "--prod"flag.Aliases: -c.7--crossOrigin none anonymous usecredentialsDefine the crossorigin attribute settingof elements that provide CORS support.Default: none.8--deleteOutputPath true falseDelete the output path before building.Default: true.9--deployUrl deployUrlURL where files will be deployed.10--experimentalRollupPass true falseConcatenate modules with Rollupbefore bundling them with Webpack.Default: false.11--extractCss true falseExtract css from global styles into cssfiles instead of js ones.Default: false.12--extractLicenses true falseExtract all licenses in a separate file.Default: false.13--forkTypeChecker true falseRun the TypeScript type checker in aforked process.Default: true.14--help true false json JSONShows a help messagecommand in the console.forDefault: false.21this

Angular CLI15-i18nMissingTranslation warning error ignoreHow to handle missing translations fori18n.Default: warning.16--index index17--localize true false18--main mainThe full path for the main entry point tothe app, relative to the currentworkspace.19--namedChunks true falseUse file name for lazy loaded chunks.Configures the generationapplication's HTML index.oftheDefault: true.20--ngswConfigPath ngswConfigPathPath to ngsw-config.json.21--optimization true falseEnablesoutput.22--outputHashing none all media bundlesDefine the output filename cachebusting hashing mode.optimizationofthebuildDefault: none.23--outputPath outputPathThe full path for the new outputdirectory, relative to the currentworkspace. By default, writes output toa folder named dist/ in the currentproject.24--pollEnable and define the file watching polltime period in milliseconds.25--polyfills polyfillsThe full path for the polyfills file,relative to the current workspace.26--preserveSymlinks true falseDo not use the real path when resolvingmodules.Default: false.22

Angular CLI27--prod true falseShorthandfor"-configuration production". When true,sets the build configuration to theproduction target. By default, theproduction target is set up in theworkspace configuration such that allbuilds make use of bundling, limitedtree-shaking, and also limited deadcode elimination.28--progress true falseLog progress to the console whilebuilding.Default: true.27--resourcesOutputPath resourcesOutputPathThe path where style resources will beplaced, relative to outputPath.28--serviceWorker true falseGenerates a service worker config forproduction builds.Default: false.29--showCircularDependencies true falseShow circular dependency warnings onbuilds.Default: true.30--sourceMap true falseOutput sourcemaps.Default: true.31--statsJson true falseGenerates a 'stats.json' file which canbe analyzed using tools such as'webpack-bundle-analyzer'.Default: false.32--subresourceIntegrity true falseEnables the useintegrity validation.ofsubresourceDefault: false.33--tsConfig tsConfigThe full path for the TypeScriptconfiguration file, relative to thecurrent workspace.23

Angular CLI34--vendorChunk true falseUse a separate bundle containing onlyvendor libraries.Default: true.35--verbose true falseAdds more details to output logging.Default: true.36--watch true falseRun build when files change.Default: false.37--webWorkerTsConfig webWorkerTsConfigTypeScript configurationWorker modules.forFirst, move to an angular project updated using ng generate command. Replace contentof app.component.html with following contents and then, run the command. This chapteris available at https://www.tutorialspoint.com/angular cli/angular cli ng generate.htm. app-goals /app-goals router-outlet /router-outlet ExampleAn example for ng build command is given below:\ Node\ TutorialsPoint ng buildCompiling @angular/animations : es2015 as esm2015Compiling @angular/core : es2015 as esm2015Compiling @angular/compiler/testing : es2015 as esm2015Compiling @angular/animations/browser : es2015 as esm2015Compiling @angular/core/testing : es2015 as esm2015Compiling @angular/common : es2015 as esm2015Compiling @angular/platform-browser : es2015 as esm2015Compiling @angular/common/http : es2015 as esm2015Compiling @angular/common/testing : es2015 as esm2015Compiling @angular/platform-browser-dynamic : es2015 as esm2015Compiling @angular/platform-browser/testing : es2015 as esm2015Compiling @angular/router : es2015 as esm2015Compiling @angular/animations/browser/testing : es2015 as esm2015Compiling @angular/common/http/testing : es2015 as esm2015Compiling @angular/forms : es2015 as esm201524Web

Angular CLICompiling @angular/platform-browser/animations : es2015 as esm2015Compiling @angular/platform-browser-dynamic/testing : es2015 as esm2015Compiling @angular/router/testing : es2015 as esm2015Generating ES5 bundles for differential loading.ES5 bundle generation complete.chunk {polyfills} polyfills-es2015.js, polyfills-es2015.js.map (polyfills) 141kB [initial] [rendered]chunk {runtime} runtime-es2015.js, runtime-es2015.js.map (runtime) 6.16 kB[entry] [rendered]chunk {runtime} runtime-es5.js, runtime-es5.js.map (runtime) 6.16 kB [entry][rendered]chunk {styles} styles-es2015.js, styles-es2015.js.map (styles) 12.4 kB[initial] [rendered]chunk {styles} styles-es5.js, styles-es5.js.map (styles) 13.9 kB [initial][rendered]chunk {main} main-es2015.js, main-es2015.js.map (main) 61.4 kB [initial][rendered]chunk {main} main-es5.js, main-es5.js.map (main) 65 kB [initial] [rendered]chunk {polyfills-es5} polyfills-es5.js, polyfills-es5.js.map (polyfills-es5)656 kB [initial] [rendered]chunk {vendor} vendor-es2015.js, vendor-es2015.js.map (vendor) 2.67 MB[initial] [rendered]chunk {vendor} vendor-es5.js, vendor-es5.js.map (vendor) 3.11 MB [initial][rendered]Date: 2020-06-04T01:31:35.612Z - Hash: d5fd9371cdc40ae353bc - Time: 210494msHere, ng build command has built our project

Angular command-line interface (CLI) makes it easy to start with any Angular project. It comes with commands that help us create and start on our project very fast. Let us now go through the commands available to create a project, a component and services, change the port, etc. To work with Angular CLI, we need to have it installed on our system.