严格的规则适用于新的Angular应用

如何从头开始创建和配置Angular项目


简短介绍


我经常遇到这样的情况,即项目在开发之初就没有进行足够严格的配置,这是一个很大的错误,因为更改样机的设置或将来包含其他用于检查脚本类型的选项可能是整个团队的真正痛苦。 因此,请勿犯此常见错误,并从一开始就尽可能严格地配置项目。


准备开发环境


吉特


需要在任何开发环境上安装的第一件事是Git 。 在您的操作系统上下载并安装Git。


之后,您需要设置个人数据。 此信息将包含在每次提交中,然后任何团队成员都可以找到该项目上任何代码行的作者。


//    (  )   $ git config --global user.name "John Doe" $ git config --global user.email johndoe@example.com //            $ git config user.name "John Doe" $ git config user.email johndoe@example.com 

NodeJ和NVM


接下来需要配置以与Angular一起使用的是NodeJs 。 到目前为止,最好的方法是使用Node Version Manager安装NodeJ。 这样就可以轻松切换到任何版本,甚至可以针对每个项目自动进行切换。


  1. 在MacO上,必须在安装前在主目录中创建.zshrc文件。

 $ touch ~/.zshrc 

  1. 运行以下命令之一以安装或升级NVM。 团队中的版本可能已更新,因此请在此处检查最新版本。

 $ curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.1/install.sh | bash $ wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.1/install.sh | bash 

  1. 安装最新的LTS版本的NodeJ

 $ nvm install 'lts/*' 

  1. 将其设置为默认值

 $ nvm use 'lts/*' $ nvm alias default 'lts/*' 

  1. 在MacO上,将以下代码添加到〜/ .zshrc文件中,以在转到包含.nvmrc文件的目录时自动调用nvm use ,并在一行中告诉nvm使用哪个版本的nodejs。 对于其他操作系统,请阅读手册。

 # place this after nvm initialization! autoload -U add-zsh-hook load-nvmrc() { local node_version="$(nvm version)" local nvmrc_path="$(nvm_find_nvmrc)" if [ -n "$nvmrc_path" ]; then local nvmrc_node_version=$(nvm version "$(cat "${nvmrc_path}")") if [ "$nvmrc_node_version" = "N/A" ]; then nvm install elif [ "$nvmrc_node_version" != "$node_version" ]; then nvm use fi elif [ "$node_version" != "$(nvm version default)" ]; then echo "Reverting to nvm default version" nvm use default fi } add-zsh-hook chpwd load-nvmrc load-nvmrc 

CLI安装和项目创建


  1. 使用npm软件包管理器安装CLI

 $ npm install -g @angular/cli 

  1. 转到您的项目文件夹并创建一个空的Angular项目

 $ cd ~/Projects $ ng new --create-application false --new-project-root apps project-name 

我们创建了一个空项目,其中包含用于新应用程序的自定义应用程序目录。 换句话说,我们准备了单一存储库的基础。


  1. mono存储库中创建并提交第一个应用程序。

 $ cd project-name $ ng generate application --routing true --style scss website $ git add . $ git commit -m 'website application created' 

要创建其他应用程序,只需使用其他应用程序名称而不是website重复此步骤。


图书馆创作


我通常建议在libs文件夹中创建库。 为此,我们需要在angular.json文件中更改一行:


 "newProjectRoot": "apps", 

在下一行:


 "newProjectRoot": "libs", 

并执行命令:


 $ ng generate library @group-name/lib-name 

我们添加了组名,以更清楚地按域或其他原则对库进行分组。 另外,如果要在npm中发布库,则必须首先在此处创建一个名称与group-name相对应的组织。 这类似于一组相关库的名称空间,例如:


 "@angular/common" "@angular/compiler" "@angular/core" "@angular/forms" 

在以后的文章中,我将在npm中更详细地描述发布库的过程。 同时,请遵循此规则。


并且不要忘记将angular.json返回其先前的状态: "newProjectRoot": "apps"


附加配置


NodeJs版本


添加一个带有lts lts/*文本的.nvmrc文件。 您还可以指定特定版本的节点,例如12.13.1 。 如果您遵循我之前的说明,将会自动安装此版本。 您也可以使用$ nvm use手动激活此版本。


 $ touch .nvmrc $ echo "lts/*" > .nvmrc 

严格检查null和undefined


将以下规则添加到tsconfig.json以启用对null和undefined的严格检查。 这将保护您免受读取未定义或空变量的属性的常见错误的影响。


 "compilerOptions": { "strictNullChecks": true, } 

更妙的是 ,如果您要进行更严格的检查,请在编译器中包含所有规则:


 /* Strict Type-Checking Options */ "strict": true, /* Enable all strict type-checking options. */ // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ // "strictNullChecks": true, /* Enable strict null checks. */ // "strictFunctionTypes": true, /* Enable strict checking of function types. */ // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ /* Additional Checks */ "noUnusedLocals": true, /* Report errors on unused locals. */ "noUnusedParameters": true, /* Report errors on unused parameters. */ "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ 

为了使TypeScript不仅在TS文件中更严格,而且在Angular模板中也更加严格,您需要在tsconfig.json中启用'fullTemplateTypeCheck'选项:


 { "compilerOptions": { ... }, "angularCompilerOptions": { "fullTemplateTypeCheck": true ... } } 

添加这些规则后,尝试构建项目并修复发现的所有错误。


 $ npm run build 

严格的TsLint规则


以最严格的设置启用所有tslint规则 ,只需为此替换tslint.json


 "extends": "tslint:recommended", 


 "extends": "tslint:all", 

并添加以下规则以禁用一些其他规则


 "no-implicit-dependencies": false, "no-submodule-imports": false, "completed-docs": false, "prefer-function-over-method": false, "file-name-casing": [ true, "kebab-case" ], "no-object-literal-type-assertion": [ true, { "allow-arguments": true } ], "no-floating-promises": false, "promise-function-async": false, "no-unsafe-any": false, "no-any": false, "comment-format": [ true, "check-space" ], "newline-per-chained-call": false, "typedef": [ true, "call-signature", "arrow-call-signature", "parameter", "arrow-parameter", "property-declaration", "object-destructuring", "array-destructuring" ] 

在开发过程中,禁用或配置您不喜欢的规则。 并且不要忘记在您的IDE中包含tslint支持


添加这些规则后,请尝试使用lint运行项目并修复所有错误。


 $ npm run lint 

带有stylelint的Lint SCSS


添加stylelint以检查您的sssss代码的质量


 $ npm install stylelint stylelint-config-standard --save-dev $ touch .stylelintrc 

并在.stylelintrc中配置规则


 { "extends": "stylelint-config-standard", "rules": {} } 

添加以下行以在package.json中运行stylelint


 "scripts": { "lint-all-scss": "stylelint \"**/*.scss\"", "lint-all-scss-fix": "npm run lint-all-scss -- --fix" } 

在开发过程中,请禁用或配置不适合您的规则。 并且不要忘记在IDE中包含stylelint支持


 $ npm run lint-all-scss-fix 

更漂亮


漂亮的用来格式化代码。 对于某些代码行,Prettier并没有为您提供所需的结果,但是尽管使用它有很多好处,但还有很多。


 $ npm install --save-dev --save-exact prettier 

.prettierrc配置文件添加到项目中


 { "printWidth": 120, "tabWidth": 2, "arrowParens": "always", "bracketSpacing": true, "endOfLine": "lf", "semi": true, "singleQuote": true, "quoteProps": "consistent", "trailingComma": "all" } 

还有一个.prettierignore文件,其中包含被忽略的文件和文件夹


 karma.conf.js protractor.conf.js ng-package.json package.json tsconfig.lib.json tsconfig.app.json tsconfig.spec.json tslint.json tsconfig.json browserslist .gitkeep favicon.ico 

在package.json中添加用于运行漂亮脚本的脚本


 "scripts": { "prettier": "prettier --write \"{apps,libs}/**/*\"", "prettier:check": "prettier --check \"{apps,libs}/**/*\"" }, 

之后,运行更漂亮的修复项目中的所有文件


 $ npm run prettier 

挂钩


为了运行linter,formatter或其他脚本,我们可以配置git hooks。 我们将为此使用以下软件包:


  • 沙哑的 -套钩
  • 非常快速 -仅对修改后的文件启动更漂亮的

 $ npm i husky pretty-quick -D 

下一步是为我们的钩子编写脚本。 我更喜欢为shell脚本创建一个tools文件夹。 我们将配置3个钩子:


  1. pre-commit-在提交之前执行的钩子。 在这种情况下,我们将更漂亮地保存修改后的文件。
  2. commit-msg-一个钩子,您可以在其中更改提交文本,我们使用它在提交文本中添加分支名称。
  3. pre-push-在git push之前执行的钩子。 我们用它来启动lint。

package.json中的 Husky配置:


 "husky": { "hooks": { "pre-commit": "pretty-quick --staged", "commit-msg": "node ./tools/commit-msg.js", "pre-push": "./tools/pre-push.sh" } }, 

脚本./tools/commit-msg.js


 const fs = require('fs'); const { execSync } = require('child_process'); const message = fs.readFileSync(process.env.HUSKY_GIT_PARAMS, 'utf8').trim(); const currentBranch = getCurrentBranch(); fs.writeFileSync(process.env.HUSKY_GIT_PARAMS, `${currentBranch}: ${message}`); process.exit(0); function getCurrentBranch() { const branches = execSync('git branch', { encoding: 'utf8' }); return branches .split('\n') .find((b) => b.charAt(0) === '*') .trim() .substring(2); } 

脚本./tools/pre-push.sh


 #!/usr/bin/env bash npm run lint-all-scss || exit npm run lint || exit 

您还可以将测试运行和e2e添加到预推脚本中。


即将推出...


本文是有关设置Angular项目的系列文章中的第一篇。 在以下文章中,我计划涵盖以下主题:


  • 配置与Travis和Docker的持续集成
  • 服务器端渲染
  • 翻译
  • 测验
  • 管理模块的状态和结构
  • 具有Nrwl.Nx的Mono存储库

订阅,提出问题。 您还可以在此存储库中看到本文中描述的示例。




也可以通过MediumTelegramTwitter加入我们的社区。

Source: https://habr.com/ru/post/zh-CN481444/


All Articles