Maison  >  Article  >  interface Web  >  Que sont les schémas angulaires ? Comment construire ? (explication détaillée)

Que sont les schémas angulaires ? Comment construire ? (explication détaillée)

青灯夜游
青灯夜游avant
2022-02-22 11:20:502596parcourir

Que sont les schémas Angular ? Comment développer vos schémas angulaires localement ? L'article suivant vous donnera une introduction détaillée et utilisera un exemple pour mieux vous familiariser avec celui-ci. J'espère qu'il vous sera utile !

Que sont les schémas angulaires ? Comment construire ? (explication détaillée)

Qu'est-ce que les schémas angulaires ?

Angular Schematics est un générateur de code spécifique à Angular, basé sur un modèle. Bien sûr, il génère non seulement du code, il peut également modifier notre code. Il nous permet d'implémenter certaines de nos propres automatisations basées sur Angular CLI. [Recommandations de didacticiel associées : "Tutoriel angulaire"]

Je pense que lors du développement de projets angulaires, tout le monde a utilisé ng generate composant nom-du composant, ng add @angular/materials code>, <code>ng generate module module-name, voici quelques CLI qui ont été implémentées pour nous dans Angular Alors, comment devrions-nous implémenter la CLI basée sur nos propres projets dans nos propres projets ? Cet article sera présenté sur la base de notre pratique dans ng-devui-adminng generate component component-name, ng add @angular/materials, ng generate module module-name,这些都是 Angular 中已经为我们实现的一些 CLI,那么我们应该如何在自己的项目中去实现基于自己项目的 CLI 呢?本文将会基于我们在 ng-devui-admin 中的实践来进行介绍。欢迎大家持续的关注,后续我们将会推出更加丰富的 CLI 帮助大家更快搭建一个 Admin 页面。

如何在本地开发你的 Angular Schematics

在本地开发你需要先安装 schematics 脚手架

npm install -g @angular-devkit/schematics-cli

# 安装完成之后新建一个schematics项目
schematics blank --name=your-schematics

新建项目之后你会看到如下目录结构,代表你已经成功创建一个 shematics 项目。

Que sont les schémas angulaires ? Comment construire ? (explication détaillée)

重要文件介绍

  • tsconfig.json: 主要与项目打包编译相关,在这不做具体介绍

  • collection.json:与你的 CLI 命令相关,用于定义你的相关命令

{
  "$schema": "../node_modules/@angular-devkit/schematics/collection-schema.json",
  "schematics": {
    "first-schematics": {
      "description": "A blank schematic.",
      "factory": "./first-schematics/index#firstSchematics"
    }
  }
}

first-schematics: 命令的名字,可以在项目中通过 ng g first-schematics:first-schematics 来运行该命令。description: 对该条命令的描述。factory: 命令执行的入口函数 通常还会有另外一个属性 schema,我们将在后面进行讲解。

  • index.ts:在该文件中实现你命令的相关逻辑
import { Rule, SchematicContext, Tree } from &#39;@angular-devkit/schematics&#39;;

export function firstSchematics(_options: any): Rule {
  return (tree: Tree, _context: SchematicContext) => {
    return tree;
  };
}

在这里我们先看几个需要了解的参数:tree:在这里你可以将 tree 理解为我们整个的 angular 项目,你可以通过 tree 新增文件,修改文件,以及删除文件。_context:该参数为 schematics 运行的上下文,比如你可以通过 context 执行 npm installRule:为我们制定的操作逻辑。

实现一个 ng-add 指令

现在我们通过实现一个 ng-add 指令来更好的熟悉。

同样是基于以上我们已经创建好的项目。

新建命令相关的文件

首先我们在 src 目录下新建一个目录 ng-add,然后在该目录下添加三个文件 index.ts, schema.json, schema.ts,之后你的目录结构应该如下:

Que sont les schémas angulaires ? Comment construire ? (explication détaillée)

配置 <span style="font-size: 18px;">collection.json</span>

之后我们在 collection.json 中配置该条命令:

{
  "$schema": "../node_modules/@angular-devkit/schematics/collection-schema.json",
  "schematics": {
    ...,
    "ng-add": {
      "factory": "./ng-add/index",
      "description": "Some description about your schematics",
      "schema": "./ng-add/schema.json"
    }
  }
}

<span style="font-size: 18px;">files</span> 目录中加入我们想要插入的文件

关于 template 的语法可以参考 ejs 语法

app.component.html.template

<div class="my-app">
  <% if (defaultLanguage === &#39;zh-cn&#39;) { %>你好,Angular Schematics!<% } else { %>Hello, My First Angular Schematics!<% } %>
  <h1>{{ title }}</h1>
</div>

app.component.scss.template

.app {
  display: flex;
  justify-content: center;
  align-item: center;
}

app.component.ts.template

import { Component } from &#39;@angular/core&#39;;

@Component({
  selector: &#39;app-root&#39;,
  templateUrl: &#39;./app.component.html&#39;,
  styleUrls: [&#39;./app.component.scss&#39;]
})
export class AppComponent {
  title = <% if (defaultLanguage === &#39;zh-cn&#39;) { %>&#39;你好&#39;<% } else { %>&#39;Hello&#39;<% } %>;
}

开始实现命令逻辑

  • schema.json:在该文件中定义与用户的交互
{
  "$schema": "http://json-schema.org/schema",
  "id": "SchematicsDevUI",
  "title": "DevUI Options Schema",
  "type": "object",
  "properties": {
    "defaultLanguage": {
      "type": "string",
      "description": "Choose the default language",
      "default": "zh-cn",
      "x-prompt": {
        "message": "Please choose the default language you want to use: ",
        "type": "list",
        "items": [
          {
            "value": "zh-cn",
            "label": "简体中文 (zh-ch)"
          },
          {
            "value": "en-us",
            "label": "English (en-us)"
          }
        ]
      }
    },
    "i18n": {
      "type": "boolean",
      "default": true,
      "description": "Config i18n for the project",
      "x-prompt": "Would you like to add i18n? (default: Y)"
    }
  },
  "required": []
}

在以上的定义中,我们的命令将会接收两个参数分别为 defaultLanguagei18n,我们以 defaultLanguage. Nous apprécions votre attention continue. Nous lancerons une CLI plus riche à l'avenir pour vous aider à créer une page Admin plus rapidement.

🎜Comment développer vos schémas angulaires localement🎜🎜Pour développer localement, vous devez d'abord installer l'échafaudage schémas🎜
{
  "defaultLanguage": {
    "type": "string",
    "description": "Choose the default language",
    "default": "zh-cn",
    "x-prompt": {
      "message": "Please choose the default language you want to use: ",
      "type": "list",
      "items": [
        {
          "value": "zh-cn",
          "label": "简体中文 (zh-ch)"
        },
        {
          "value": "en-us",
          "label": "English (en-us)"
        }
      ]
    }
  }
}
🎜Après avoir créé un nouveau projet, vous verrez la structure de répertoires suivante, ce qui signifie que vous avoir créé avec succès un projet shematics. 🎜🎜Que sont les schémas angulaires ? Comment construire ? (explication détaillée)🎜🎜Important Introduction du fichier🎜
  • 🎜tsconfig.json : principalement lié au packaging et à la compilation du projet, pas d'introduction détaillée ici🎜
  • 🎜collection.json : lié à votre commande CLI, utilisé pour définir vos commandes associées🎜
export interface Schema {
  defaultLanguage: string;
  i18n: boolean;
}
🎜first-schematics : le nom de la commande, qui peut être transmis dans le projet ng g first-schematics:first-schematics pour exécuter la commande. description : Description de cette commande. factory : fonction de saisie pour l'exécution des commandes Il existe généralement un autre attribut schéma, que nous expliquerons plus tard. 🎜
  • index.ts : implémentez la logique pertinente de votre commande dans ce fichier
import {
  apply,
  applyTemplates,
  chain,
  mergeWith,
  move,
  Rule,
  SchematicContext,
  SchematicsException,
  Tree,
  url
} from &#39;@angular-devkit/schematics&#39;;
import { NodePackageInstallTask } from &#39;@angular-devkit/schematics/tasks&#39;;
import { Schema as AddOptions } from &#39;./schema&#39;;

let projectWorkspace: {
  root: string;
  sourceRoot: string;
  defaultProject: string;
};

export type packgeType = &#39;dependencies&#39; | &#39;devDependencies&#39; | &#39;scripts&#39;;
export const PACKAGES_I18N = [
  &#39;@devui-design/icons@^1.2.0&#39;,
  &#39;@ngx-translate/core@^13.0.0&#39;,
  &#39;@ngx-translate/http-loader@^6.0.0&#39;,
  &#39;ng-devui@^11.1.0&#39;
];
export const PACKAGES = [&#39;@devui-design/icons@^1.2.0&#39;, &#39;ng-devui@^11.1.0&#39;];
export const PACKAGE_JSON_PATH = &#39;package.json&#39;;
export const ANGULAR_JSON_PATH = &#39;angular.json&#39;;

export default function (options: AddOptions): Rule {
  return (tree: Tree, context: SchematicContext) => {
    // 获取项目空间中我们需要的相关变量
    getWorkSpace(tree);

    // 根据是否选择i18n插入不同的packages
    const packages = options.i18n ? PACKAGES_I18N : PACKAGES;
    addPackage(tree, packages, &#39;dependencies&#39;);

    // 执行 npm install
    context.addTask(new NodePackageInstallTask());

    // 自定义的一系列 Rules
    return chain([removeOriginalFiles(), addSourceFiles(options)]);
  };
}
🎜Ici, nous examinons d'abord quelques paramètres qui doivent être compris : tree : Ici, vous pouvez comprendre l'arborescence comme l'ensemble de notre projet angulaire. Vous pouvez ajouter des fichiers, modifier des fichiers et supprimer des fichiers via l'arborescence. _context : ce paramètre est le contexte dans lequel schematics s'exécute. Par exemple, vous pouvez exécuter npm install via context. . Règle : La logique de fonctionnement formulée pour nous. 🎜🎜Implémentation d'une directive ng-add🎜🎜Maintenant, nous allons mieux nous familiariser avec elle en implémentant une directive ng-add. 🎜🎜Il s'appuie également sur les projets que nous avons créés ci-dessus. 🎜🎜Créer de nouveaux fichiers liés aux commandes🎜🎜Nous créons d'abord un nouveau répertoire sous le src directoryng-add, puis ajoutez trois fichiers index.ts, schema.json, schema.ts dans ce répertoire >, alors votre structure de répertoires doit être la suivante : 🎜🎜Que sont les schémas angulaires ? Comment construire ? (explication détaillée)🎜🎜Configuration<span style="font-size: 18px;">collection .json</span>🎜🎜Après cela, nous configurons cette commande dans collection.json : 🎜
// getWorkSpace
function getWorkSpace(tree: Tree) {
  let angularJSON;
  let buffer = tree.read(ANGULAR_JSON_PATH);
  if (buffer) {
    angularJSON = JSON.parse(buffer.toString());
  } else {
    throw new SchematicsException(
      &#39;Please make sure the project is an Angular project.&#39;
    );
  }

  let defaultProject = angularJSON.defaultProject;
  projectWorkspace = {
    root: &#39;/&#39;,
    sourceRoot: angularJSON.projects[defaultProject].sourceRoot,
    defaultProject
  };

  return projectWorkspace;
}
🎜Ajoutez ce que nous voulons aux <span style="font-size: 18px;">fichiers</span> Fichiers insérés🎜🎜Pour la syntaxe du template, veuillez vous référer à syntaxe ejs🎜🎜🎜app.component.html.template🎜
// removeOriginalFiles
// 根据自己的需要选择需要删除的文件
function removeOriginalFiles() {
  return (tree: Tree) => {
    [
      `${projectWorkspace.sourceRoot}/app/app.component.ts`,
      `${projectWorkspace.sourceRoot}/app/app.component.html`,
      `${projectWorkspace.sourceRoot}/app/app.component.scss`,
      `${projectWorkspace.sourceRoot}/app/app.component.css`
    ]
      .filter((f) => tree.exists(f))
      .forEach((f) => tree.delete(f));
  };
}
🎜app.component.scss.template🎜
// addSourceFiles
function addSourceFiles(options: AddOptions): Rule {
  return chain([
    mergeWith(
      apply(url(&#39;./files&#39;), [
        applyTemplates({
          defaultLanguage: options.defaultLanguage
        }),
        move(`${projectWorkspace.sourceRoot}/app`)
      ])
    )
  ]);
}
🎜app.component. ts.template🎜<pre class="brush:js;toolbar:false;">// readJson function readJson(tree: Tree, file: string, type?: string): any { if (!tree.exists(file)) { return null; } const sourceFile = tree.read(file)!.toString(&amp;#39;utf-8&amp;#39;); try { const json = JSON.parse(sourceFile); if (type &amp;&amp; !json[type]) { json[type] = {}; } return json; } catch (error) { console.log(`Failed when parsing file ${file}.`); throw error; } } // writeJson export function writeJson(tree: Tree, file: string, source: any): void { tree.overwrite(file, JSON.stringify(source, null, 2)); } // readPackageJson function readPackageJson(tree: Tree, type?: string): any { return readJson(tree, PACKAGE_JSON_PATH, type); } // writePackageJson function writePackageJson(tree: Tree, json: any): any { return writeJson(tree, PACKAGE_JSON_PATH, json); } // addPackage function addPackage( tree: Tree, packages: string | string[], type: packgeType = &amp;#39;dependencies&amp;#39; ): Tree { const packageJson = readPackageJson(tree, type); if (packageJson == null) { return tree; } if (!Array.isArray(packages)) { packages = [packages]; } packages.forEach((pck) =&gt; { const splitPosition = pck.lastIndexOf(&amp;#39;@&amp;#39;); packageJson[type][pck.substr(0, splitPosition)] = pck.substr( splitPosition + 1 ); }); writePackageJson(tree, packageJson); return tree; }</pre>🎜<strong><span style="font-size: 18px;">Commencez à implémenter la logique de commande</span></strong>🎜<ul><li> <code>schéma. json : Définir l'interaction avec l'utilisateur dans ce fichierrrreee🎜Dans la définition ci-dessus, notre commande recevra deux paramètres : defaultLanguage, i18n , nous utilisons defaultLanguage comme exemple pour expliquer la configuration des paramètres associée : 🎜
{
  "defaultLanguage": {
    "type": "string",
    "description": "Choose the default language",
    "default": "zh-cn",
    "x-prompt": {
      "message": "Please choose the default language you want to use: ",
      "type": "list",
      "items": [
        {
          "value": "zh-cn",
          "label": "简体中文 (zh-ch)"
        },
        {
          "value": "en-us",
          "label": "English (en-us)"
        }
      ]
    }
  }
}

type 代表该参数的类型是 stringdefault 为该参数的默认值为 zh-cnx-prompt 定义与用户的交互,message 为我们对用户进行的相关提问,在这里我们的 typelist 代表我们会为用户提供 items 中列出的选项供用户进行选择。

  • schema.ts:在该文件中定义我们接收到的参数类型
export interface Schema {
  defaultLanguage: string;
  i18n: boolean;
}
  • index.ts:在该文件中实现我们的操作逻辑,假设在此次 ng-add 操作中,我们根据用户输入的 defaultLanguage, i18n 来对用户的项目进行相应的更改,并且插入相关的 npm 包,再进行安装。
import {
  apply,
  applyTemplates,
  chain,
  mergeWith,
  move,
  Rule,
  SchematicContext,
  SchematicsException,
  Tree,
  url
} from &#39;@angular-devkit/schematics&#39;;
import { NodePackageInstallTask } from &#39;@angular-devkit/schematics/tasks&#39;;
import { Schema as AddOptions } from &#39;./schema&#39;;

let projectWorkspace: {
  root: string;
  sourceRoot: string;
  defaultProject: string;
};

export type packgeType = &#39;dependencies&#39; | &#39;devDependencies&#39; | &#39;scripts&#39;;
export const PACKAGES_I18N = [
  &#39;@devui-design/icons@^1.2.0&#39;,
  &#39;@ngx-translate/core@^13.0.0&#39;,
  &#39;@ngx-translate/http-loader@^6.0.0&#39;,
  &#39;ng-devui@^11.1.0&#39;
];
export const PACKAGES = [&#39;@devui-design/icons@^1.2.0&#39;, &#39;ng-devui@^11.1.0&#39;];
export const PACKAGE_JSON_PATH = &#39;package.json&#39;;
export const ANGULAR_JSON_PATH = &#39;angular.json&#39;;

export default function (options: AddOptions): Rule {
  return (tree: Tree, context: SchematicContext) => {
    // 获取项目空间中我们需要的相关变量
    getWorkSpace(tree);

    // 根据是否选择i18n插入不同的packages
    const packages = options.i18n ? PACKAGES_I18N : PACKAGES;
    addPackage(tree, packages, &#39;dependencies&#39;);

    // 执行 npm install
    context.addTask(new NodePackageInstallTask());

    // 自定义的一系列 Rules
    return chain([removeOriginalFiles(), addSourceFiles(options)]);
  };
}

下面时使用到的函数的具体实现:

// getWorkSpace
function getWorkSpace(tree: Tree) {
  let angularJSON;
  let buffer = tree.read(ANGULAR_JSON_PATH);
  if (buffer) {
    angularJSON = JSON.parse(buffer.toString());
  } else {
    throw new SchematicsException(
      &#39;Please make sure the project is an Angular project.&#39;
    );
  }

  let defaultProject = angularJSON.defaultProject;
  projectWorkspace = {
    root: &#39;/&#39;,
    sourceRoot: angularJSON.projects[defaultProject].sourceRoot,
    defaultProject
  };

  return projectWorkspace;
}
// removeOriginalFiles
// 根据自己的需要选择需要删除的文件
function removeOriginalFiles() {
  return (tree: Tree) => {
    [
      `${projectWorkspace.sourceRoot}/app/app.component.ts`,
      `${projectWorkspace.sourceRoot}/app/app.component.html`,
      `${projectWorkspace.sourceRoot}/app/app.component.scss`,
      `${projectWorkspace.sourceRoot}/app/app.component.css`
    ]
      .filter((f) => tree.exists(f))
      .forEach((f) => tree.delete(f));
  };
}

将 files 下的文件拷贝到指定的路径下,关于 chain, mergeWith, apply, template 的详细使用方法可以参考 Schematics

// addSourceFiles
function addSourceFiles(options: AddOptions): Rule {
  return chain([
    mergeWith(
      apply(url(&#39;./files&#39;), [
        applyTemplates({
          defaultLanguage: options.defaultLanguage
        }),
        move(`${projectWorkspace.sourceRoot}/app`)
      ])
    )
  ]);
}
// readJson
function readJson(tree: Tree, file: string, type?: string): any {
  if (!tree.exists(file)) {
    return null;
  }

  const sourceFile = tree.read(file)!.toString(&#39;utf-8&#39;);
  try {
    const json = JSON.parse(sourceFile);
    if (type && !json[type]) {
      json[type] = {};
    }
    return json;
  } catch (error) {
    console.log(`Failed when parsing file ${file}.`);
    throw error;
  }
}

// writeJson
export function writeJson(tree: Tree, file: string, source: any): void {
  tree.overwrite(file, JSON.stringify(source, null, 2));
}

// readPackageJson
function readPackageJson(tree: Tree, type?: string): any {
  return readJson(tree, PACKAGE_JSON_PATH, type);
}

// writePackageJson
function writePackageJson(tree: Tree, json: any): any {
  return writeJson(tree, PACKAGE_JSON_PATH, json);
}

// addPackage
function addPackage(
  tree: Tree,
  packages: string | string[],
  type: packgeType = &#39;dependencies&#39;
): Tree {
  const packageJson = readPackageJson(tree, type);

  if (packageJson == null) {
    return tree;
  }

  if (!Array.isArray(packages)) {
    packages = [packages];
  }
  packages.forEach((pck) => {
    const splitPosition = pck.lastIndexOf(&#39;@&#39;);
    packageJson[type][pck.substr(0, splitPosition)] = pck.substr(
      splitPosition + 1
    );
  });

  writePackageJson(tree, packageJson);
  return tree;
}

为了保持 index.ts 文件的简洁,可以将相关操作的方法抽取到一个新的文件中进行引用。

测试 <span style="font-size: 18px;">ng-add</span>

至此我们已经完成了 ng-add 命令,现在我们对该命令进行测试:

  • ng new test 初始化一个 Angular 项目
  • cd test && mkdir libs 在项目中添加一个 libs 文件夹,将图中标蓝的文件拷贝到其中

Que sont les schémas angulaires ? Comment construire ? (explication détaillée)

  • 之后在命令行中执行 npm link libs/
  • link 完成之后 cd libs && npm run build && cd ..
  • 现在执行 ng add first-schematics 之后会看到如下提示

Que sont les schémas angulaires ? Comment construire ? (explication détaillée)

  • 最后我们通过 npm start 来查看执行的结果如下

Que sont les schémas angulaires ? Comment construire ? (explication détaillée)

结语

综上简单介绍了一个 Schematics 的实现,更多的一些应用欢迎大家查看 ng-devui-admin 中的实现。

更多编程相关知识,请访问:编程学习!!

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Cet article est reproduit dans:. en cas de violation, veuillez contacter admin@php.cn Supprimer