diff --git a/adev-es/src/content/tools/libraries/angular-package-format.en.md b/adev-es/src/content/tools/libraries/angular-package-format.en.md new file mode 100644 index 0000000..82d1282 --- /dev/null +++ b/adev-es/src/content/tools/libraries/angular-package-format.en.md @@ -0,0 +1,385 @@ +# Angular package format + +This document describes the Angular Package Format \(APF\). +APF is an Angular specific specification for the structure and format of npm packages that is used by all first-party Angular packages \(`@angular/core`, `@angular/material`, etc.\) and most third-party Angular libraries. + +APF enables a package to work seamlessly under most common scenarios that use Angular. +Packages that use APF are compatible with the tooling offered by the Angular team as well as wider JavaScript ecosystem. +It is recommended that third-party library developers follow the same npm package format. + +HELPFUL: APF is versioned along with the rest of Angular, and every major version improves the package format. +You can find the versions of the specification prior to v13 in this [google doc](https://docs.google.com/document/d/1CZC2rcpxffTDfRDs6p1cfbmKNLA6x5O-NtkJglDaBVs/preview). + +## Why specify a package format? + +In today's JavaScript landscape, developers consume packages in many different ways, using many different toolchains \(webpack, Rollup, esbuild, etc.\). +These tools may understand and require different inputs - some tools may be able to process the latest ES language version, while others may benefit from directly consuming an older ES version. + +The Angular distribution format supports all of the commonly used development tools and workflows, and adds emphasis on optimizations that result either in smaller application payload size or faster development iteration cycle \(build time\). + +Developers can rely on Angular CLI and [ng-packagr](https://github.com/ng-packagr/ng-packagr) \(a build tool Angular CLI uses\) to produce packages in the Angular package format. +See the [Creating Libraries](tools/libraries/creating-libraries) guide for more details. + +## File layout + +The following example shows a simplified version of the `@angular/core` package's file layout, with an explanation for each file in the package. + +```markdown +node_modules/@angular/core +├── README.md +├── package.json +├── index.d.ts +├── fesm2022 +│ ├── core.mjs +│ ├── core.mjs.map +│ ├── testing.mjs +│ └── testing.mjs.map +└── testing + └── index.d.ts +``` + +This table describes the file layout under `node_modules/@angular/core` annotated to describe the purpose of files and directories: + +| Files | Purpose | +|:--- |:--- | +| `README.md` | Package README, used by npmjs web UI. | +| `package.json` | Primary `package.json`, describing the package itself as well as all available entrypoints and code formats. This file contains the "exports" mapping used by runtimes and tools to perform module resolution. | +| `index.d.ts` | Bundled `.d.ts` for the primary entrypoint `@angular/core`. | +| `fesm2022/`
  ─ `core.mjs`
  ─ `core.mjs.map`
  ─ `testing.mjs`
  ─ `testing.mjs.map` | Code for all entrypoints in flattened \(FESM\) ES2022 format, along with source maps. | +| `testing/` | Directory representing the "testing" entrypoint. | +| `testing/index.d.ts` | Bundled `.d.ts` for the `@angular/core/testing` entrypoint. | + +## `package.json` + +The primary `package.json` contains important package metadata, including the following: + +* It [declares](#esm-declaration) the package to be in EcmaScript Module \(ESM\) format +* It contains an [`"exports"` field](#exports) which defines the available source code formats of all entrypoints +* It contains [keys](#legacy-resolution-keys) which define the available source code formats of the primary `@angular/core` entrypoint, for tools which do not understand `"exports"`. + These keys are considered deprecated, and could be removed as the support for `"exports"` rolls out across the ecosystem. + +* It declares whether the package contains [side effects](#side-effects) + +### ESM declaration + +The top-level `package.json` contains the key: + + + +{ + "type": "module" +} + + + +This informs resolvers that code within the package is using EcmaScript Modules as opposed to CommonJS modules. + +### `"exports"` + +The `"exports"` field has the following structure: + + + +"exports": { + "./schematics/*": { + "default": "./schematics/*.js" + }, + "./package.json": { + "default": "./package.json" + }, + ".": { + "types": "./core.d.ts", + "default": "./fesm2022/core.mjs" + }, + "./testing": { + "types": "./testing/testing.d.ts", + "default": "./fesm2022/testing.mjs" + } +} + + + +Of primary interest are the `"."` and the `"./testing"` keys, which define the available code formats for the `@angular/core` primary entrypoint and the `@angular/core/testing` secondary entrypoint, respectively. +For each entrypoint, the available formats are: + +| Formats | Details | +|:--- |:--- | +| Typings \(`.d.ts` files\) | `.d.ts` files are used by TypeScript when depending on a given package. | +| `default` | ES2022 code flattened into a single source. + +Tooling that is aware of these keys may preferentially select a desirable code format from `"exports"`. + +Libraries may want to expose additional static files which are not captured by the exports of the JavaScript-based entry-points such as Sass mixins or pre-compiled CSS. + +For more information, see [Managing assets in a library](tools/libraries/creating-libraries#managing-assets-in-a-library). + +### Legacy resolution keys + +In addition to `"exports"`, the top-level `package.json` also defines legacy module resolution keys for resolvers that don't support `"exports"`. +For `@angular/core` these are: + + + +{ + "module": "./fesm2022/core.mjs", + "typings": "./core.d.ts", +} + + + +As shown in the preceding code snippet, a module resolver can use these keys to load a specific code format. + +### Side effects + +The last function of `package.json` is to declare whether the package has [side effects](#sideeffects-flag). + + + +{ + "sideEffects": false +} + + + +Most Angular packages should not depend on top-level side effects, and thus should include this declaration. + +## Entrypoints and code splitting + +Packages in the Angular Package Format contain one primary entrypoint and zero or more secondary entrypoints \(for example, `@angular/common/http`\). +Entrypoints serve several functions. + +1. They define the module specifiers from which users import code \(for example, `@angular/core` and `@angular/core/testing`\). + + Users typically perceive these entrypoints as distinct groups of symbols, with different purposes or capability. + + Specific entrypoints might only be used for special purposes, such as testing. + Such APIs can be separated out from the primary entrypoint to reduce the chance of them being used accidentally or incorrectly. + +1. They define the granularity at which code can be lazily loaded. + + Many modern build tools are only capable of "code splitting" \(aka lazy loading\) at the ES Module level. + The Angular Package Format uses primarily a single "flat" ES Module per entry point. This means that most build tooling is not able to split code with a single entry point into multiple output chunks. + +The general rule for APF packages is to use entrypoints for the smallest sets of logically connected code possible. +For example, the Angular Material package publishes each logical component or set of components as a separate entrypoint - one for Button, one for Tabs, etc. +This allows each Material component to be lazily loaded separately, if desired. + +Not all libraries require such granularity. +Most libraries with a single logical purpose should be published as a single entrypoint. +`@angular/core` for example uses a single entrypoint for the runtime, because the Angular runtime is generally used as a single entity. + +### Resolution of secondary entry points + +Secondary entrypoints can be resolved via the `"exports"` field of the `package.json` for the package. + +## README.md + +The README file in the Markdown format that is used to display description of a package on npm and GitHub. + +Example README content of @angular/core package: + + + +Angular +======= + +The sources for this package are in the main [Angular](https://github.com/angular/angular) repo.Please file issues and pull requests against that repo. + +License: MIT + + + +## Partial compilation + +Libraries in the Angular Package Format must be published in "partial compilation" mode. +This is a compilation mode for `ngc` which produces compiled Angular code that is not tied to a specific Angular runtime version, in contrast to the full compilation used for applications, where the Angular compiler and runtime versions must match exactly. + +To partially compile Angular code, use the `compilationMode` flag in the `angularCompilerOptions` property of your `tsconfig.json`: + + + +{ + … + "angularCompilerOptions": { + "compilationMode": "partial", + } +} + + + +Partially compiled library code is then converted to fully compiled code during the application build process by the Angular CLI. + +If your build pipeline does not use the Angular CLI then refer to the [Consuming partial ivy code outside the Angular CLI](tools/libraries/creating-libraries#consuming-partial-ivy-code-outside-the-angular-cli) guide. + +## Optimizations + +### Flattening of ES modules + +The Angular Package Format specifies that code be published in "flattened" ES module format. +This significantly reduces the build time of Angular applications as well as download and parse time of the final application bundle. +Please check out the excellent post ["The cost of small modules"](https://nolanlawson.com/2016/08/15/the-cost-of-small-modules) by Nolan Lawson. + +The Angular compiler can generate index ES module files. Tools like Rollup can use these files to generate flattened modules in a *Flattened ES Module* (FESM) file format. + +FESM is a file format created by flattening all ES Modules accessible from an entrypoint into a single ES Module. +It's formed by following all imports from a package and copying that code into a single file while preserving all public ES exports and removing all private imports. + +The abbreviated name, FESM, pronounced *phe-som*, can be followed by a number such as FESM2020. +The number refers to the language level of the JavaScript inside the module. +Accordingly a FESM2022 file would be ESM+ES2022 and include import/export statements and ES2022 source code. + +To generate a flattened ES Module index file, use the following configuration options in your tsconfig.json file: + + + +{ + "compilerOptions": { + … + "module": "esnext", + "target": "es2022", + … + }, + "angularCompilerOptions": { + … + "flatModuleOutFile": "my-ui-lib.js", + "flatModuleId": "my-ui-lib" + } +} + + + +Once the index file \(for example, `my-ui-lib.js`\) is generated by ngc, bundlers and optimizers like Rollup can be used to produce the flattened ESM file. + +### "sideEffects" flag + +By default, EcmaScript Modules are side-effectful: importing from a module ensures that any code at the top level of that module should run. +This is often undesirable, as most side-effectful code in typical modules is not truly side-effectful, but instead only affects specific symbols. +If those symbols are not imported and used, it's often desirable to remove them in an optimization process known as tree-shaking, and the side-effectful code can prevent this. + +Build tools such as webpack support a flag which allows packages to declare that they do not depend on side-effectful code at the top level of their modules, giving the tools more freedom to tree-shake code from the package. +The end result of these optimizations should be smaller bundle size and better code distribution in bundle chunks after code-splitting. +This optimization can break your code if it contains non-local side-effects - this is however not common in Angular applications and it's usually a sign of bad design. +The recommendation is for all packages to claim the side-effect free status by setting the `sideEffects` property to `false`, and that developers follow the [Angular Style Guide](/style-guide) which naturally results in code without non-local side-effects. + +More info: [webpack docs on side effects](https://github.com/webpack/webpack/tree/master/examples/side-effects) + +### ES2022 language level + +ES2022 Language level is now the default language level that is consumed by Angular CLI and other tooling. +The Angular CLI down-levels the bundle to a language level that is supported by all targeted browsers at application build time. + +### d.ts bundling / type definition flattening + +As of APF v8, it is recommended to bundle TypeScript definitions. +Bundling of type definitions can significantly speed up compilations for users, especially if there are many individual `.ts` source files in your library. + +Angular uses [`rollup-plugin-dts`](https://github.com/Swatinem/rollup-plugin-dts) to flatten `.d.ts` files (using `rollup`, similar to how FESM files are created). + +Using rollup for `.d.ts` bundling is beneficial as it supports code splitting between entry-points. +For example, consider you have multiple entrypoints relying on the same shared type, a shared `.d.ts` file would be created along with the larger flattened `.d.ts` files. +This is desirable and avoids duplication of types. + +### Tslib + +As of APF v10, it is recommended to add tslib as a direct dependency of your primary entry-point. +This is because the tslib version is tied to the TypeScript version used to compile your library. + +## Examples + + + + + + +## Definition of terms + +The following terms are used throughout this document intentionally. +In this section are the definitions of all of them to provide additional clarity. + +### Package + +The smallest set of files that are published to NPM and installed together, for example `@angular/core`. +This package includes a manifest called package.json, compiled source code, typescript definition files, source maps, metadata, etc. +The package is installed with `npm install @angular/core`. + +### Symbol + +A class, function, constant, or variable contained in a module and optionally made visible to the external world via a module export. + +### Module + +Short for ECMAScript Modules. +A file containing statements that import and export symbols. +This is identical to the definition of modules in the ECMAScript spec. + +### ESM + +Short for ECMAScript Modules \(see above\). + +### FESM + +Short for Flattened ES Modules and consists of a file format created by flattening all ES Modules accessible from an entry point into a single ES Module. + +### Module ID + +The identifier of a module used in the import statements \(for example, `@angular/core`\). +The ID often maps directly to a path on the filesystem, but this is not always the case due to various module resolution strategies. + +### Module specifier + +A module identifier \(see above\). + +### Module resolution strategy + +Algorithm used to convert Module IDs to paths on the filesystem. +Node.js has one that is well specified and widely used, TypeScript supports several module resolution strategies, [Closure Compiler](https://developers.google.com/closure/compiler) has yet another strategy. + +### Module format + +Specification of the module syntax that covers at minimum the syntax for the importing and exporting from a file. +Common module formats are CommonJS \(CJS, typically used for Node.js applications\) or ECMAScript Modules \(ESM\). +The module format indicates only the packaging of the individual modules, but not the JavaScript language features used to make up the module content. +Because of this, the Angular team often uses the language level specifier as a suffix to the module format, \(for example, ESM+ES2022 specifies that the module is in ESM format and contains ES2022 code\). + +### Bundle + +An artifact in the form of a single JS file, produced by a build tool \(for example, [webpack](https://webpack.js.org) or [Rollup](https://rollupjs.org)\) that contains symbols originating in one or more modules. +Bundles are a browser-specific workaround that reduce network strain that would be caused if browsers were to start downloading hundreds if not tens of thousands of files. +Node.js typically doesn't use bundles. +Common bundle formats are UMD and System.register. + +### Language level + +The language of the code \(ES2022\). +Independent of the module format. + +### Entry point + +A module intended to be imported by the user. +It is referenced by a unique module ID and exports the public API referenced by that module ID. +An example is `@angular/core` or `@angular/core/testing`. +Both entry points exist in the `@angular/core` package, but they export different symbols. +A package can have many entry points. + +### Deep import + +A process of retrieving symbols from modules that are not Entry Points. +These module IDs are usually considered to be private APIs that can change over the lifetime of the project or while the bundle for the given package is being created. + +### Top-Level import + +An import coming from an entry point. +The available top-level imports are what define the public API and are exposed in "@angular/name" modules, such as `@angular/core` or `@angular/common`. + +### Tree-shaking + +The process of identifying and removing code not used by an application - also known as dead code elimination. +This is a global optimization performed at the application level using tools like [Rollup](https://rollupjs.org), [Closure Compiler](https://developers.google.com/closure/compiler), or [Terser](https://github.com/terser/terser). + +### AOT compiler + +The Ahead of Time Compiler for Angular. + +### Flattened type definitions + +The bundled TypeScript definitions generated from [API Extractor](https://api-extractor.com). diff --git a/adev-es/src/content/tools/libraries/angular-package-format.md b/adev-es/src/content/tools/libraries/angular-package-format.md index 82d1282..58a2428 100644 --- a/adev-es/src/content/tools/libraries/angular-package-format.md +++ b/adev-es/src/content/tools/libraries/angular-package-format.md @@ -1,28 +1,28 @@ -# Angular package format +# Formato de paquete Angular -This document describes the Angular Package Format \(APF\). -APF is an Angular specific specification for the structure and format of npm packages that is used by all first-party Angular packages \(`@angular/core`, `@angular/material`, etc.\) and most third-party Angular libraries. +Este documento describe el formato de paquete Angular \(APF\). +APF es una especificación específica de Angular para la estructura y formato de paquetes npm que es usada por todos los paquetes propios de Angular \(`@angular/core`, `@angular/material`, etc.\) y la mayoría de las librerías de Angular de terceros. -APF enables a package to work seamlessly under most common scenarios that use Angular. -Packages that use APF are compatible with the tooling offered by the Angular team as well as wider JavaScript ecosystem. -It is recommended that third-party library developers follow the same npm package format. +APF permite que un paquete funcione sin problemas en la mayoría de los escenarios comunes que usan Angular. +Los paquetes que usan APF son compatibles con las herramientas ofrecidas por el equipo de Angular así como con el ecosistema JavaScript más amplio. +Se recomienda que los desarrolladores de librerías de terceros sigan el mismo formato de paquete npm. -HELPFUL: APF is versioned along with the rest of Angular, and every major version improves the package format. -You can find the versions of the specification prior to v13 in this [google doc](https://docs.google.com/document/d/1CZC2rcpxffTDfRDs6p1cfbmKNLA6x5O-NtkJglDaBVs/preview). +ÚTIL: APF tiene versiones junto con el resto de Angular, y cada versión mayor mejora el formato de paquete. +Puedes encontrar las versiones de la especificación anteriores a v13 en este [documento de google](https://docs.google.com/document/d/1CZC2rcpxffTDfRDs6p1cfbmKNLA6x5O-NtkJglDaBVs/preview). -## Why specify a package format? +## ¿Por qué especificar un formato de paquete? -In today's JavaScript landscape, developers consume packages in many different ways, using many different toolchains \(webpack, Rollup, esbuild, etc.\). -These tools may understand and require different inputs - some tools may be able to process the latest ES language version, while others may benefit from directly consuming an older ES version. +En el panorama actual de JavaScript, los desarrolladores consumen paquetes de muchas maneras diferentes, usando muchos toolchains diferentes \(webpack, Rollup, esbuild, etc.\). +Estas herramientas pueden entender y requerir diferentes entradas - algunas herramientas pueden procesar la última versión del lenguaje ES, mientras que otras pueden beneficiarse de consumir directamente una versión más antigua de ES. -The Angular distribution format supports all of the commonly used development tools and workflows, and adds emphasis on optimizations that result either in smaller application payload size or faster development iteration cycle \(build time\). +El formato de distribución de Angular soporta todas las herramientas de desarrollo y flujos de trabajo comúnmente usados, y agrega énfasis en optimizaciones que resultan ya sea en un tamaño de carga útil de aplicación más pequeño o un ciclo de iteración de desarrollo más rápido \(tiempo de compilación\). -Developers can rely on Angular CLI and [ng-packagr](https://github.com/ng-packagr/ng-packagr) \(a build tool Angular CLI uses\) to produce packages in the Angular package format. -See the [Creating Libraries](tools/libraries/creating-libraries) guide for more details. +Los desarrolladores pueden confiar en Angular CLI y [ng-packagr](https://github.com/ng-packagr/ng-packagr) \(una herramienta de compilación que usa Angular CLI\) para producir paquetes en el formato de paquete Angular. +Consulta la guía [Creando librerías](tools/libraries/creating-libraries) para más detalles. -## File layout +## Diseño de archivos -The following example shows a simplified version of the `@angular/core` package's file layout, with an explanation for each file in the package. +El siguiente ejemplo muestra una versión simplificada del diseño de archivos del paquete `@angular/core`, con una explicación para cada archivo en el paquete. ```markdown node_modules/@angular/core @@ -38,31 +38,31 @@ node_modules/@angular/core └── index.d.ts ``` -This table describes the file layout under `node_modules/@angular/core` annotated to describe the purpose of files and directories: +Esta tabla describe el diseño de archivos bajo `node_modules/@angular/core` anotado para describir el propósito de archivos y directorios: -| Files | Purpose | +| Archivos | Propósito | |:--- |:--- | -| `README.md` | Package README, used by npmjs web UI. | -| `package.json` | Primary `package.json`, describing the package itself as well as all available entrypoints and code formats. This file contains the "exports" mapping used by runtimes and tools to perform module resolution. | -| `index.d.ts` | Bundled `.d.ts` for the primary entrypoint `@angular/core`. | -| `fesm2022/`
  ─ `core.mjs`
  ─ `core.mjs.map`
  ─ `testing.mjs`
  ─ `testing.mjs.map` | Code for all entrypoints in flattened \(FESM\) ES2022 format, along with source maps. | -| `testing/` | Directory representing the "testing" entrypoint. | -| `testing/index.d.ts` | Bundled `.d.ts` for the `@angular/core/testing` entrypoint. | +| `README.md` | README del paquete, usado por la interfaz web de npmjs. | +| `package.json` | `package.json` principal, describiendo el paquete en sí así como todos los puntos de entrada disponibles y formatos de código. Este archivo contiene el mapeo "exports" usado por runtimes y herramientas para realizar resolución de módulos. | +| `index.d.ts` | `.d.ts` empaquetado para el punto de entrada principal `@angular/core`. | +| `fesm2022/`
  ─ `core.mjs`
  ─ `core.mjs.map`
  ─ `testing.mjs`
  ─ `testing.mjs.map` | Código para todos los puntos de entrada en formato ES2022 aplanado \(FESM\), junto con mapas de código fuente. | +| `testing/` | Directorio representando el punto de entrada "testing". | +| `testing/index.d.ts` | `.d.ts` empaquetado para el punto de entrada `@angular/core/testing`. | ## `package.json` -The primary `package.json` contains important package metadata, including the following: +El `package.json` principal contiene metadatos importantes del paquete, incluyendo lo siguiente: -* It [declares](#esm-declaration) the package to be in EcmaScript Module \(ESM\) format -* It contains an [`"exports"` field](#exports) which defines the available source code formats of all entrypoints -* It contains [keys](#legacy-resolution-keys) which define the available source code formats of the primary `@angular/core` entrypoint, for tools which do not understand `"exports"`. - These keys are considered deprecated, and could be removed as the support for `"exports"` rolls out across the ecosystem. +* [Declara](#esm-declaration) que el paquete está en formato de módulo EcmaScript \(ESM\) +* Contiene un [campo `"exports"`](#exports) que define los formatos de código fuente disponibles de todos los puntos de entrada +* Contiene [claves](#legacy-resolution-keys) que definen los formatos de código fuente disponibles del punto de entrada principal `@angular/core`, para herramientas que no entienden `"exports"`. + Estas claves se consideran deprecadas, y podrían eliminarse a medida que el soporte para `"exports"` se implemente en todo el ecosistema. -* It declares whether the package contains [side effects](#side-effects) +* Declara si el paquete contiene [efectos secundarios](#side-effects) -### ESM declaration +### Declaración ESM -The top-level `package.json` contains the key: +El `package.json` de nivel superior contiene la clave: @@ -72,11 +72,11 @@ The top-level `package.json` contains the key: -This informs resolvers that code within the package is using EcmaScript Modules as opposed to CommonJS modules. +Esto informa a los resolvers que el código dentro del paquete está usando módulos EcmaScript en oposición a módulos CommonJS. ### `"exports"` -The `"exports"` field has the following structure: +El campo `"exports"` tiene la siguiente estructura: @@ -99,24 +99,24 @@ The `"exports"` field has the following structure: -Of primary interest are the `"."` and the `"./testing"` keys, which define the available code formats for the `@angular/core` primary entrypoint and the `@angular/core/testing` secondary entrypoint, respectively. -For each entrypoint, the available formats are: +De interés principal son las claves `"."` y `"./testing"`, que definen los formatos de código disponibles para el punto de entrada principal `@angular/core` y el punto de entrada secundario `@angular/core/testing`, respectivamente. +Para cada punto de entrada, los formatos disponibles son: -| Formats | Details | +| Formatos | Detalles | |:--- |:--- | -| Typings \(`.d.ts` files\) | `.d.ts` files are used by TypeScript when depending on a given package. | -| `default` | ES2022 code flattened into a single source. +| Tipados \(archivos `.d.ts`\) | Los archivos `.d.ts` son usados por TypeScript cuando se depende de un paquete dado. | +| `default` | Código ES2022 aplanado en una sola fuente. -Tooling that is aware of these keys may preferentially select a desirable code format from `"exports"`. +Las herramientas que conocen estas claves pueden seleccionar preferentemente un formato de código deseable desde `"exports"`. -Libraries may want to expose additional static files which are not captured by the exports of the JavaScript-based entry-points such as Sass mixins or pre-compiled CSS. +Las librerías pueden querer exponer archivos estáticos adicionales que no están capturados por las exportaciones de los puntos de entrada basados en JavaScript, como mixins de Sass o CSS pre-compilado. -For more information, see [Managing assets in a library](tools/libraries/creating-libraries#managing-assets-in-a-library). +Para más información, consulta [Gestionando recursos en una librería](tools/libraries/creating-libraries#managing-assets-in-a-library). -### Legacy resolution keys +### Claves de resolución heredadas -In addition to `"exports"`, the top-level `package.json` also defines legacy module resolution keys for resolvers that don't support `"exports"`. -For `@angular/core` these are: +Además de `"exports"`, el `package.json` de nivel superior también define claves de resolución de módulos heredadas para resolvers que no soportan `"exports"`. +Para `@angular/core` estas son: @@ -127,11 +127,11 @@ For `@angular/core` these are: -As shown in the preceding code snippet, a module resolver can use these keys to load a specific code format. +Como se muestra en el fragmento de código anterior, un resolver de módulos puede usar estas claves para cargar un formato de código específico. -### Side effects +### Efectos secundarios -The last function of `package.json` is to declare whether the package has [side effects](#sideeffects-flag). +La última función de `package.json` es declarar si el paquete tiene [efectos secundarios](#sideeffects-flag). @@ -141,42 +141,42 @@ The last function of `package.json` is to declare whether the package has [side -Most Angular packages should not depend on top-level side effects, and thus should include this declaration. +La mayoría de los paquetes de Angular no deberían depender de efectos secundarios de nivel superior, y por lo tanto deberían incluir esta declaración. -## Entrypoints and code splitting +## Puntos de entrada y división de código -Packages in the Angular Package Format contain one primary entrypoint and zero or more secondary entrypoints \(for example, `@angular/common/http`\). -Entrypoints serve several functions. +Los paquetes en el formato de paquete Angular contienen un punto de entrada principal y cero o más puntos de entrada secundarios \(por ejemplo, `@angular/common/http`\). +Los puntos de entrada sirven para varias funciones. -1. They define the module specifiers from which users import code \(for example, `@angular/core` and `@angular/core/testing`\). +1. Definen los especificadores de módulo desde los cuales los usuarios importan código \(por ejemplo, `@angular/core` y `@angular/core/testing`\). - Users typically perceive these entrypoints as distinct groups of symbols, with different purposes or capability. + Los usuarios típicamente perciben estos puntos de entrada como grupos distintos de símbolos, con diferentes propósitos o capacidades. - Specific entrypoints might only be used for special purposes, such as testing. - Such APIs can be separated out from the primary entrypoint to reduce the chance of them being used accidentally or incorrectly. + Puntos de entrada específicos podrían usarse solo para propósitos especiales, como pruebas. + Tales APIs pueden separarse del punto de entrada principal para reducir la posibilidad de que se usen accidental o incorrectamente. -1. They define the granularity at which code can be lazily loaded. +1. Definen la granularidad a la que el código puede cargarse de forma diferida. - Many modern build tools are only capable of "code splitting" \(aka lazy loading\) at the ES Module level. - The Angular Package Format uses primarily a single "flat" ES Module per entry point. This means that most build tooling is not able to split code with a single entry point into multiple output chunks. + Muchas herramientas de compilación modernas solo son capaces de "dividir código" \(también conocido como lazy loading\) a nivel de módulo ES. + El formato de paquete Angular usa principalmente un único módulo ES "aplanado" por punto de entrada. Esto significa que la mayoría de las herramientas de compilación no pueden dividir código con un único punto de entrada en múltiples fragmentos de salida. -The general rule for APF packages is to use entrypoints for the smallest sets of logically connected code possible. -For example, the Angular Material package publishes each logical component or set of components as a separate entrypoint - one for Button, one for Tabs, etc. -This allows each Material component to be lazily loaded separately, if desired. +La regla general para paquetes APF es usar puntos de entrada para los conjuntos más pequeños posibles de código lógicamente conectado. +Por ejemplo, el paquete Angular Material publica cada componente lógico o conjunto de componentes como un punto de entrada separado - uno para Button, uno para Tabs, etc. +Esto permite que cada componente de Material se cargue de forma diferida por separado, si se desea. -Not all libraries require such granularity. -Most libraries with a single logical purpose should be published as a single entrypoint. -`@angular/core` for example uses a single entrypoint for the runtime, because the Angular runtime is generally used as a single entity. +No todas las librerías requieren tal granularidad. +La mayoría de las librerías con un único propósito lógico deberían publicarse como un único punto de entrada. +`@angular/core` por ejemplo usa un único punto de entrada para el runtime, porque el runtime de Angular generalmente se usa como una sola entidad. -### Resolution of secondary entry points +### Resolución de puntos de entrada secundarios -Secondary entrypoints can be resolved via the `"exports"` field of the `package.json` for the package. +Los puntos de entrada secundarios pueden resolverse a través del campo `"exports"` del `package.json` para el paquete. ## README.md -The README file in the Markdown format that is used to display description of a package on npm and GitHub. +El archivo README en formato Markdown que se usa para mostrar la descripción de un paquete en npm y GitHub. -Example README content of @angular/core package: +Ejemplo de contenido README del paquete @angular/core: @@ -189,12 +189,12 @@ License: MIT -## Partial compilation +## Compilación parcial -Libraries in the Angular Package Format must be published in "partial compilation" mode. -This is a compilation mode for `ngc` which produces compiled Angular code that is not tied to a specific Angular runtime version, in contrast to the full compilation used for applications, where the Angular compiler and runtime versions must match exactly. +Las librerías en el formato de paquete Angular deben publicarse en modo "compilación parcial". +Este es un modo de compilación para `ngc` que produce código Angular compilado que no está vinculado a una versión específica del runtime de Angular, en contraste con la compilación completa usada para aplicaciones, donde las versiones del compilador y runtime de Angular deben coincidir exactamente. -To partially compile Angular code, use the `compilationMode` flag in the `angularCompilerOptions` property of your `tsconfig.json`: +Para compilar parcialmente código Angular, usa la bandera `compilationMode` en la propiedad `angularCompilerOptions` de tu `tsconfig.json`: @@ -207,28 +207,28 @@ To partially compile Angular code, use the `compilationMode` flag in the `angula -Partially compiled library code is then converted to fully compiled code during the application build process by the Angular CLI. +El código de librería compilado parcialmente se convierte luego a código completamente compilado durante el proceso de compilación de la aplicación por el Angular CLI. -If your build pipeline does not use the Angular CLI then refer to the [Consuming partial ivy code outside the Angular CLI](tools/libraries/creating-libraries#consuming-partial-ivy-code-outside-the-angular-cli) guide. +Si tu pipeline de compilación no usa el Angular CLI, consulta la guía [Consumiendo código partial ivy fuera del Angular CLI](tools/libraries/creating-libraries#consuming-partial-ivy-code-outside-the-angular-cli). -## Optimizations +## Optimizaciones -### Flattening of ES modules +### Aplanamiento de módulos ES -The Angular Package Format specifies that code be published in "flattened" ES module format. -This significantly reduces the build time of Angular applications as well as download and parse time of the final application bundle. -Please check out the excellent post ["The cost of small modules"](https://nolanlawson.com/2016/08/15/the-cost-of-small-modules) by Nolan Lawson. +El formato de paquete Angular especifica que el código se publique en formato de módulo ES "aplanado". +Esto reduce significativamente el tiempo de compilación de aplicaciones de Angular así como el tiempo de descarga y análisis del bundle final de la aplicación. +Por favor revisa el excelente post ["The cost of small modules"](https://nolanlawson.com/2016/08/15/the-cost-of-small-modules) de Nolan Lawson. -The Angular compiler can generate index ES module files. Tools like Rollup can use these files to generate flattened modules in a *Flattened ES Module* (FESM) file format. +El compilador de Angular puede generar archivos de módulos ES índice. Herramientas como Rollup pueden usar estos archivos para generar módulos aplanados en un formato de archivo *Módulo ES Aplanado* (FESM). -FESM is a file format created by flattening all ES Modules accessible from an entrypoint into a single ES Module. -It's formed by following all imports from a package and copying that code into a single file while preserving all public ES exports and removing all private imports. +FESM es un formato de archivo creado aplanando todos los módulos ES accesibles desde un punto de entrada en un único módulo ES. +Se forma siguiendo todas las importaciones desde un paquete y copiando ese código en un único archivo mientras se preservan todas las exportaciones públicas de ES y se eliminan todas las importaciones privadas. -The abbreviated name, FESM, pronounced *phe-som*, can be followed by a number such as FESM2020. -The number refers to the language level of the JavaScript inside the module. -Accordingly a FESM2022 file would be ESM+ES2022 and include import/export statements and ES2022 source code. +El nombre abreviado, FESM, pronunciado *fe-som*, puede ir seguido de un número como FESM2020. +El número se refiere al nivel de lenguaje del JavaScript dentro del módulo. +Por lo tanto, un archivo FESM2022 sería ESM+ES2022 e incluiría declaraciones de importación/exportación y código fuente ES2022. -To generate a flattened ES Module index file, use the following configuration options in your tsconfig.json file: +Para generar un archivo índice de módulo ES aplanado, usa las siguientes opciones de configuración en tu archivo tsconfig.json: @@ -248,138 +248,138 @@ To generate a flattened ES Module index file, use the following configuration op -Once the index file \(for example, `my-ui-lib.js`\) is generated by ngc, bundlers and optimizers like Rollup can be used to produce the flattened ESM file. +Una vez que el archivo índice \(por ejemplo, `my-ui-lib.js`\) es generado por ngc, bundlers y optimizadores como Rollup pueden usarse para producir el archivo ESM aplanado. -### "sideEffects" flag +### Bandera "sideEffects" -By default, EcmaScript Modules are side-effectful: importing from a module ensures that any code at the top level of that module should run. -This is often undesirable, as most side-effectful code in typical modules is not truly side-effectful, but instead only affects specific symbols. -If those symbols are not imported and used, it's often desirable to remove them in an optimization process known as tree-shaking, and the side-effectful code can prevent this. +Por defecto, los módulos EcmaScript tienen efectos secundarios: importar desde un módulo asegura que cualquier código en el nivel superior de ese módulo debería ejecutarse. +Esto es a menudo indeseable, ya que la mayoría del código con efectos secundarios en módulos típicos no es verdaderamente con efectos secundarios, sino que solo afecta símbolos específicos. +Si esos símbolos no se importan y usan, a menudo es deseable eliminarlos en un proceso de optimización conocido como tree-shaking, y el código con efectos secundarios puede prevenir esto. -Build tools such as webpack support a flag which allows packages to declare that they do not depend on side-effectful code at the top level of their modules, giving the tools more freedom to tree-shake code from the package. -The end result of these optimizations should be smaller bundle size and better code distribution in bundle chunks after code-splitting. -This optimization can break your code if it contains non-local side-effects - this is however not common in Angular applications and it's usually a sign of bad design. -The recommendation is for all packages to claim the side-effect free status by setting the `sideEffects` property to `false`, and that developers follow the [Angular Style Guide](/style-guide) which naturally results in code without non-local side-effects. +Herramientas de compilación como webpack soportan una bandera que permite que los paquetes declaren que no dependen de código con efectos secundarios en el nivel superior de sus módulos, dando a las herramientas más libertad para hacer tree-shaking del código del paquete. +El resultado final de estas optimizaciones debería ser un tamaño de bundle más pequeño y mejor distribución de código en fragmentos de bundle después de la división de código. +Esta optimización puede romper tu código si contiene efectos secundarios no locales - esto sin embargo no es común en aplicaciones de Angular y generalmente es un signo de mal diseño. +La recomendación es que todos los paquetes reclamen el estado libre de efectos secundarios estableciendo la propiedad `sideEffects` en `false`, y que los desarrolladores sigan la [Guía de estilo de Angular](/style-guide) que naturalmente resulta en código sin efectos secundarios no locales. -More info: [webpack docs on side effects](https://github.com/webpack/webpack/tree/master/examples/side-effects) +Más información: [documentación de webpack sobre efectos secundarios](https://github.com/webpack/webpack/tree/master/examples/side-effects) -### ES2022 language level +### Nivel de lenguaje ES2022 -ES2022 Language level is now the default language level that is consumed by Angular CLI and other tooling. -The Angular CLI down-levels the bundle to a language level that is supported by all targeted browsers at application build time. +ES2022 es ahora el nivel de lenguaje predeterminado que es consumido por Angular CLI y otras herramientas. +El Angular CLI reduce el nivel del bundle a un nivel de lenguaje que es soportado por todos los navegadores objetivo en tiempo de compilación de la aplicación. -### d.ts bundling / type definition flattening +### Empaquetado de d.ts / aplanamiento de definiciones de tipo -As of APF v8, it is recommended to bundle TypeScript definitions. -Bundling of type definitions can significantly speed up compilations for users, especially if there are many individual `.ts` source files in your library. +A partir de APF v8, se recomienda empaquetar definiciones de TypeScript. +El empaquetado de definiciones de tipo puede acelerar significativamente las compilaciones para los usuarios, especialmente si hay muchos archivos fuente `.ts` individuales en tu librería. -Angular uses [`rollup-plugin-dts`](https://github.com/Swatinem/rollup-plugin-dts) to flatten `.d.ts` files (using `rollup`, similar to how FESM files are created). +Angular usa [`rollup-plugin-dts`](https://github.com/Swatinem/rollup-plugin-dts) para aplanar archivos `.d.ts` (usando `rollup`, similar a cómo se crean los archivos FESM). -Using rollup for `.d.ts` bundling is beneficial as it supports code splitting between entry-points. -For example, consider you have multiple entrypoints relying on the same shared type, a shared `.d.ts` file would be created along with the larger flattened `.d.ts` files. -This is desirable and avoids duplication of types. +Usar rollup para empaquetado de `.d.ts` es beneficioso ya que soporta división de código entre puntos de entrada. +Por ejemplo, considera que tienes múltiples puntos de entrada que dependen del mismo tipo compartido, se crearía un archivo `.d.ts` compartido junto con los archivos `.d.ts` aplanados más grandes. +Esto es deseable y evita duplicación de tipos. ### Tslib -As of APF v10, it is recommended to add tslib as a direct dependency of your primary entry-point. -This is because the tslib version is tied to the TypeScript version used to compile your library. +A partir de APF v10, se recomienda agregar tslib como una dependencia directa de tu punto de entrada principal. +Esto es porque la versión de tslib está vinculada a la versión de TypeScript usada para compilar tu librería. -## Examples +## Ejemplos -## Definition of terms +## Definición de términos -The following terms are used throughout this document intentionally. -In this section are the definitions of all of them to provide additional clarity. +Los siguientes términos se usan a lo largo de este documento intencionalmente. +En esta sección están las definiciones de todos ellos para proporcionar claridad adicional. -### Package +### Paquete -The smallest set of files that are published to NPM and installed together, for example `@angular/core`. -This package includes a manifest called package.json, compiled source code, typescript definition files, source maps, metadata, etc. -The package is installed with `npm install @angular/core`. +El conjunto más pequeño de archivos que se publican en NPM y se instalan juntos, por ejemplo `@angular/core`. +Este paquete incluye un manifiesto llamado package.json, código fuente compilado, archivos de definición de TypeScript, mapas de código fuente, metadatos, etc. +El paquete se instala con `npm install @angular/core`. -### Symbol +### Símbolo -A class, function, constant, or variable contained in a module and optionally made visible to the external world via a module export. +Una clase, función, constante o variable contenida en un módulo y opcionalmente hecha visible al mundo externo a través de una exportación de módulo. -### Module +### Módulo -Short for ECMAScript Modules. -A file containing statements that import and export symbols. -This is identical to the definition of modules in the ECMAScript spec. +Abreviatura de módulos EcmaScript. +Un archivo que contiene declaraciones que importan y exportan símbolos. +Esto es idéntico a la definición de módulos en la especificación EcmaScript. ### ESM -Short for ECMAScript Modules \(see above\). +Abreviatura de módulos EcmaScript \(ver arriba\). ### FESM -Short for Flattened ES Modules and consists of a file format created by flattening all ES Modules accessible from an entry point into a single ES Module. +Abreviatura de módulos ES aplanados y consiste en un formato de archivo creado aplanando todos los módulos ES accesibles desde un punto de entrada en un único módulo ES. -### Module ID +### ID de módulo -The identifier of a module used in the import statements \(for example, `@angular/core`\). -The ID often maps directly to a path on the filesystem, but this is not always the case due to various module resolution strategies. +El identificador de un módulo usado en las declaraciones de importación \(por ejemplo, `@angular/core`\). +El ID a menudo mapea directamente a una ruta en el sistema de archivos, pero esto no siempre es el caso debido a varias estrategias de resolución de módulos. -### Module specifier +### Especificador de módulo -A module identifier \(see above\). +Un identificador de módulo \(ver arriba\). -### Module resolution strategy +### Estrategia de resolución de módulos -Algorithm used to convert Module IDs to paths on the filesystem. -Node.js has one that is well specified and widely used, TypeScript supports several module resolution strategies, [Closure Compiler](https://developers.google.com/closure/compiler) has yet another strategy. +Algoritmo usado para convertir IDs de módulo a rutas en el sistema de archivos. +Node.js tiene uno que está bien especificado y ampliamente usado, TypeScript soporta varias estrategias de resolución de módulos, [Closure Compiler](https://developers.google.com/closure/compiler) tiene otra estrategia diferente. -### Module format +### Formato de módulo -Specification of the module syntax that covers at minimum the syntax for the importing and exporting from a file. -Common module formats are CommonJS \(CJS, typically used for Node.js applications\) or ECMAScript Modules \(ESM\). -The module format indicates only the packaging of the individual modules, but not the JavaScript language features used to make up the module content. -Because of this, the Angular team often uses the language level specifier as a suffix to the module format, \(for example, ESM+ES2022 specifies that the module is in ESM format and contains ES2022 code\). +Especificación de la sintaxis del módulo que cubre como mínimo la sintaxis para importar y exportar desde un archivo. +Formatos de módulo comunes son CommonJS \(CJS, típicamente usado para aplicaciones Node.js\) o módulos EcmaScript \(ESM\). +El formato de módulo indica solo el empaquetado de los módulos individuales, pero no las características del lenguaje JavaScript usadas para formar el contenido del módulo. +Debido a esto, el equipo de Angular a menudo usa el especificador de nivel de lenguaje como un sufijo al formato de módulo, \(por ejemplo, ESM+ES2022 especifica que el módulo está en formato ESM y contiene código ES2022\). ### Bundle -An artifact in the form of a single JS file, produced by a build tool \(for example, [webpack](https://webpack.js.org) or [Rollup](https://rollupjs.org)\) that contains symbols originating in one or more modules. -Bundles are a browser-specific workaround that reduce network strain that would be caused if browsers were to start downloading hundreds if not tens of thousands of files. -Node.js typically doesn't use bundles. -Common bundle formats are UMD and System.register. +Un artefacto en forma de un único archivo JS, producido por una herramienta de compilación \(por ejemplo, [webpack](https://webpack.js.org) o [Rollup](https://rollupjs.org)\) que contiene símbolos originados en uno o más módulos. +Los bundles son una solución alternativa específica del navegador que reduce la carga de red que sería causada si los navegadores comenzaran a descargar cientos si no decenas de miles de archivos. +Node.js típicamente no usa bundles. +Formatos de bundle comunes son UMD y System.register. -### Language level +### Nivel de lenguaje -The language of the code \(ES2022\). -Independent of the module format. +El lenguaje del código \(ES2022\). +Independiente del formato de módulo. -### Entry point +### Punto de entrada -A module intended to be imported by the user. -It is referenced by a unique module ID and exports the public API referenced by that module ID. -An example is `@angular/core` or `@angular/core/testing`. -Both entry points exist in the `@angular/core` package, but they export different symbols. -A package can have many entry points. +Un módulo destinado a ser importado por el usuario. +Se referencia por un ID de módulo único y exporta la API pública referenciada por ese ID de módulo. +Un ejemplo es `@angular/core` o `@angular/core/testing`. +Ambos puntos de entrada existen en el paquete `@angular/core`, pero exportan diferentes símbolos. +Un paquete puede tener muchos puntos de entrada. -### Deep import +### Importación profunda -A process of retrieving symbols from modules that are not Entry Points. -These module IDs are usually considered to be private APIs that can change over the lifetime of the project or while the bundle for the given package is being created. +Un proceso de recuperar símbolos de módulos que no son puntos de entrada. +Estos IDs de módulo generalmente se consideran APIs privadas que pueden cambiar durante la vida del proyecto o mientras se crea el bundle para el paquete dado. -### Top-Level import +### Importación de nivel superior -An import coming from an entry point. -The available top-level imports are what define the public API and are exposed in "@angular/name" modules, such as `@angular/core` or `@angular/common`. +Una importación proveniente de un punto de entrada. +Las importaciones de nivel superior disponibles son las que definen la API pública y están expuestas en módulos "@angular/name", como `@angular/core` o `@angular/common`. ### Tree-shaking -The process of identifying and removing code not used by an application - also known as dead code elimination. -This is a global optimization performed at the application level using tools like [Rollup](https://rollupjs.org), [Closure Compiler](https://developers.google.com/closure/compiler), or [Terser](https://github.com/terser/terser). +El proceso de identificar y eliminar código no usado por una aplicación - también conocido como eliminación de código muerto. +Esta es una optimización global realizada a nivel de aplicación usando herramientas como [Rollup](https://rollupjs.org), [Closure Compiler](https://developers.google.com/closure/compiler), o [Terser](https://github.com/terser/terser). -### AOT compiler +### Compilador AOT -The Ahead of Time Compiler for Angular. +El compilador Ahead of Time para Angular. -### Flattened type definitions +### Definiciones de tipo aplanadas -The bundled TypeScript definitions generated from [API Extractor](https://api-extractor.com). +Las definiciones de TypeScript empaquetadas generadas desde [API Extractor](https://api-extractor.com). diff --git a/adev-es/src/content/tools/libraries/creating-libraries.en.md b/adev-es/src/content/tools/libraries/creating-libraries.en.md new file mode 100644 index 0000000..0998768 --- /dev/null +++ b/adev-es/src/content/tools/libraries/creating-libraries.en.md @@ -0,0 +1,291 @@ +# Creating libraries + +This page provides a conceptual overview of how to create and publish new libraries to extend Angular functionality. + +If you find that you need to solve the same problem in more than one application \(or want to share your solution with other developers\), you have a candidate for a library. +A simple example might be a button that sends users to your company website, that would be included in all applications that your company builds. + +## Getting started + +Use the Angular CLI to generate a new library skeleton in a new workspace with the following commands. + + + +ng new my-workspace --no-create-application +cd my-workspace +ng generate library my-lib + + + + + +You should be very careful when choosing the name of your library if you want to publish it later in a public package registry such as npm. +See [Publishing your library](tools/libraries/creating-libraries#publishing-your-library). + +Avoid using a name that is prefixed with `ng-`, such as `ng-library`. +The `ng-` prefix is a reserved keyword used from the Angular framework and its libraries. +The `ngx-` prefix is preferred as a convention used to denote that the library is suitable for use with Angular. +It is also an excellent indication to consumers of the registry to differentiate between libraries of different JavaScript frameworks. + + + +The `ng generate` command creates the `projects/my-lib` folder in your workspace, which contains a component. + +HELPFUL: For more details on how a library project is structured, refer to the [Library project files](reference/configs/file-structure#library-project-files) section of the [Project File Structure guide](reference/configs/file-structure). + +Use the monorepo model to use the same workspace for multiple projects. +See [Setting up for a multi-project workspace](reference/configs/file-structure#multiple-projects). + +When you generate a new library, the workspace configuration file, `angular.json`, is updated with a project of type `library`. + + + +"projects": { + … + "my-lib": { + "root": "projects/my-lib", + "sourceRoot": "projects/my-lib/src", + "projectType": "library", + "prefix": "lib", + "architect": { + "build": { + "builder": "@angular-devkit/build-angular:ng-packagr", + … + + + +Build, test, and lint the project with CLI commands: + + + +ng build my-lib --configuration development +ng test my-lib +ng lint my-lib + + + +Notice that the configured builder for the project is different from the default builder for application projects. +This builder, among other things, ensures that the library is always built with the [AOT compiler](tools/cli/aot-compiler). + +To make library code reusable you must define a public API for it. +This "user layer" defines what is available to consumers of your library. +A user of your library should be able to access public functionality \(such as service providers and general utility functions\) through a single import path. + +The public API for your library is maintained in the `public-api.ts` file in your library folder. +Anything exported from this file is made public when your library is imported into an application. + +Your library should supply documentation \(typically a README file\) for installation and maintenance. + +## Refactoring parts of an application into a library + +To make your solution reusable, you need to adjust it so that it does not depend on application-specific code. +Here are some things to consider in migrating application functionality to a library. + +* Declarations such as components and pipes should be designed as stateless, meaning they don't rely on or alter external variables. + If you do rely on state, you need to evaluate every case and decide whether it is application state or state that the library would manage. + +* Any observables that the components subscribe to internally should be cleaned up and disposed of during the lifecycle of those components +* Components should expose their interactions through inputs for providing context, and outputs for communicating events to other components + +* Check all internal dependencies. + * For custom classes or interfaces used in components or service, check whether they depend on additional classes or interfaces that also need to be migrated + * Similarly, if your library code depends on a service, that service needs to be migrated + * If your library code or its templates depend on other libraries \(such as Angular Material, for instance\), you must configure your library with those dependencies + +* Consider how you provide services to client applications. + + * Services should declare their own providers, rather than declaring providers in the NgModule or a component. + Declaring a provider makes that service *tree-shakable*. + This practice lets the compiler leave the service out of the bundle if it never gets injected into the application that imports the library. + For more about this, see [Tree-shakable providers](guide/di/lightweight-injection-tokens). + + * If you register global service providers expose a `provideXYZ()` provider function. + * If your library provides optional services that might not be used by all client applications, support proper tree-shaking for that case by using the [lightweight token design pattern](guide/di/lightweight-injection-tokens) + +## Integrating with the CLI using code-generation schematics + +A library typically includes *reusable code* that defines components, services, and other Angular artifacts \(pipes, directives\) that you import into a project. +A library is packaged into an npm package for publishing and sharing. +This package can also include schematics that provide instructions for generating or transforming code directly in your project, in the same way that the CLI creates a generic new component with `ng generate component`. +A schematic that is packaged with a library can, for example, provide the Angular CLI with the information it needs to generate a component that configures and uses a particular feature, or set of features, defined in that library. +One example of this is [Angular Material's navigation schematic](https://material.angular.dev/guide/schematics#navigation-schematic) which configures the CDK's [BreakpointObserver](https://material.angular.dev/cdk/layout/overview#breakpointobserver) and uses it with Material's [MatSideNav](https://material.angular.dev/components/sidenav/overview) and [MatToolbar](https://material.angular.dev/components/toolbar/overview) components. + +Create and include the following kinds of schematics: + +* Include an installation schematic so that `ng add` can add your library to a project +* Include generation schematics in your library so that `ng generate` can scaffold your defined artifacts \(components, services, tests\) in a project +* Include an update schematic so that `ng update` can update your library's dependencies and provide migrations for breaking changes in new releases + +What you include in your library depends on your task. +For example, you could define a schematic to create a dropdown that is pre-populated with canned data to show how to add it to an application. +If you want a dropdown that would contain different passed-in values each time, your library could define a schematic to create it with a given configuration. +Developers could then use `ng generate` to configure an instance for their own application. + +Suppose you want to read a configuration file and then generate a form based on that configuration. +If that form needs additional customization by the developer who is using your library, it might work best as a schematic. +However, if the form will always be the same and not need much customization by developers, then you could create a dynamic component that takes the configuration and generates the form. +In general, the more complex the customization, the more useful the schematic approach. + +For more information, see [Schematics Overview](tools/cli/schematics) and [Schematics for Libraries](tools/cli/schematics-for-libraries). + +## Publishing your library + +Use the Angular CLI and the npm package manager to build and publish your library as an npm package. + +Angular CLI uses a tool called [ng-packagr](https://github.com/ng-packagr/ng-packagr/blob/master/README.md) to create packages from your compiled code that can be published to npm. +See [Building libraries with Ivy](tools/libraries/creating-libraries#publishing-libraries) for information on the distribution formats supported by `ng-packagr` and guidance on how +to choose the right format for your library. + +You should always build libraries for distribution using the `production` configuration. +This ensures that generated output uses the appropriate optimizations and the correct package format for npm. + + + +ng build my-lib +cd dist/my-lib +npm publish + + + +## Managing assets in a library + +In your Angular library, the distributable can include additional assets like theming files, Sass mixins, or documentation \(like a changelog\). +For more information [copy assets into your library as part of the build](https://github.com/ng-packagr/ng-packagr/blob/master/docs/copy-assets.md) and [embed assets in component styles](https://github.com/ng-packagr/ng-packagr/blob/master/docs/embed-assets-css.md). + +IMPORTANT: When including additional assets like Sass mixins or pre-compiled CSS. +You need to add these manually to the conditional ["exports"](tools/libraries/angular-package-format#quotexportsquot) in the `package.json` of the primary entrypoint. + +`ng-packagr` will merge handwritten `"exports"` with the auto-generated ones, allowing for library authors to configure additional export subpaths, or custom conditions. + + + +"exports": { + ".": { + "sass": "./_index.scss", + }, + "./theming": { + "sass": "./_theming.scss" + }, + "./prebuilt-themes/indigo-pink.css": { + "style": "./prebuilt-themes/indigo-pink.css" + } +} + + + +The above is an extract from the [@angular/material](https://unpkg.com/browse/@angular/material/package.json) distributable. + +## Peer dependencies + +Angular libraries should list any `@angular/*` dependencies the library depends on as peer dependencies. +This ensures that when modules ask for Angular, they all get the exact same module. +If a library lists `@angular/core` in `dependencies` instead of `peerDependencies`, it might get a different Angular module instead, which would cause your application to break. + +## Using your own library in applications + +You don't have to publish your library to the npm package manager to use it in the same workspace, but you do have to build it first. + +To use your own library in an application: + +* Build the library. + You cannot use a library before it is built. + + + + ng build my-lib + + + +* In your applications, import from the library by name: + + + + import { myExport } from 'my-lib'; + + + +### Building and rebuilding your library + +The build step is important if you haven't published your library as an npm package and then installed the package back into your application from npm. +For instance, if you clone your git repository and run `npm install`, your editor shows the `my-lib` imports as missing if you haven't yet built your library. + +HELPFUL: When you import something from a library in an Angular application, Angular looks for a mapping between the library name and a location on disk. +When you install a library package, the mapping is in the `node_modules` folder. +When you build your own library, it has to find the mapping in your `tsconfig` paths. + +Generating a library with the Angular CLI automatically adds its path to the `tsconfig` file. +The Angular CLI uses the `tsconfig` paths to tell the build system where to find the library. + +For more information, see [Path mapping overview](https://www.typescriptlang.org/docs/handbook/module-resolution.html#path-mapping). + +If you find that changes to your library are not reflected in your application, your application is probably using an old build of the library. + +You can rebuild your library whenever you make changes to it, but this extra step takes time. +*Incremental builds* functionality improves the library-development experience. +Every time a file is changed a partial build is performed that emits the amended files. + +Incremental builds can be run as a background process in your development environment. +To take advantage of this feature add the `--watch` flag to the build command: + + + +ng build my-lib --watch + + + +IMPORTANT: The CLI `build` command uses a different builder and invokes a different build tool for libraries than it does for applications. + +* The build system for applications, `@angular-devkit/build-angular`, is based on `webpack`, and is included in all new Angular CLI projects +* The build system for libraries is based on `ng-packagr`. + It is only added to your dependencies when you add a library using `ng generate library my-lib`. + +The two build systems support different things, and even where they support the same things, they do those things differently. +This means that the TypeScript source can result in different JavaScript code in a built library than it would in a built application. + +For this reason, an application that depends on a library should only use TypeScript path mappings that point to the *built library*. +TypeScript path mappings should *not* point to the library source `.ts` files. + +## Publishing libraries + +There are two distribution formats to use when publishing a library: + +| Distribution formats | Details | +|:--- |:--- | +| Partial-Ivy \(recommended\) | Contains portable code that can be consumed by Ivy applications built with any version of Angular from v12 onwards. | +| Full-Ivy | Contains private Angular Ivy instructions, which are not guaranteed to work across different versions of Angular. This format requires that the library and application are built with the *exact* same version of Angular. This format is useful for environments where all library and application code is built directly from source. | + +For publishing to npm use the partial-Ivy format as it is stable between patch versions of Angular. + +Avoid compiling libraries with full-Ivy code if you are publishing to npm because the generated Ivy instructions are not part of Angular's public API, and so might change between patch versions. + +## Ensuring library version compatibility + +The Angular version used to build an application should always be the same or greater than the Angular versions used to build any of its dependent libraries. +For example, if you had a library using Angular version 13, the application that depends on that library should use Angular version 13 or later. +Angular does not support using an earlier version for the application. + +If you intend to publish your library to npm, compile with partial-Ivy code by setting `"compilationMode": "partial"` in `tsconfig.prod.json`. +This partial format is stable between different versions of Angular, so is safe to publish to npm. +Code with this format is processed during the application build using the same version of the Angular compiler, ensuring that the application and all of its libraries use a single version of Angular. + +Avoid compiling libraries with full-Ivy code if you are publishing to npm because the generated Ivy instructions are not part of Angular's public API, and so might change between patch versions. + +If you've never published a package in npm before, you must create a user account. +Read more in [Publishing npm Packages](https://docs.npmjs.com/getting-started/publishing-npm-packages). + +## Consuming partial-Ivy code outside the Angular CLI + +An application installs many Angular libraries from npm into its `node_modules` directory. +However, the code in these libraries cannot be bundled directly along with the built application as it is not fully compiled. +To finish compilation, use the Angular linker. + +For applications that don't use the Angular CLI, the linker is available as a [Babel](https://babeljs.io) plugin. +The plugin is to be imported from `@angular/compiler-cli/linker/babel`. + +The Angular linker Babel plugin supports build caching, meaning that libraries only need to be processed by the linker a single time, regardless of other npm operations. + +Example of integrating the plugin into a custom [webpack](https://webpack.js.org) build by registering the linker as a [Babel](https://babeljs.io) plugin using [babel-loader](https://webpack.js.org/loaders/babel-loader/#options). + + + +HELPFUL: The Angular CLI integrates the linker plugin automatically, so if consumers of your library are using the CLI, they can install Ivy-native libraries from npm without any additional configuration. diff --git a/adev-es/src/content/tools/libraries/creating-libraries.md b/adev-es/src/content/tools/libraries/creating-libraries.md index 0998768..994562c 100644 --- a/adev-es/src/content/tools/libraries/creating-libraries.md +++ b/adev-es/src/content/tools/libraries/creating-libraries.md @@ -1,13 +1,13 @@ -# Creating libraries +# Creando librerías -This page provides a conceptual overview of how to create and publish new libraries to extend Angular functionality. +Esta página proporciona una visión general conceptual de cómo crear y publicar nuevas librerías para extender la funcionalidad de Angular. -If you find that you need to solve the same problem in more than one application \(or want to share your solution with other developers\), you have a candidate for a library. -A simple example might be a button that sends users to your company website, that would be included in all applications that your company builds. +Si encuentras que necesitas resolver el mismo problema en más de una aplicación \(o quieres compartir tu solución con otros desarrolladores\), tienes un candidato para una librería. +Un ejemplo simple podría ser un botón que envía usuarios al sitio web de tu empresa, que se incluiría en todas las aplicaciones que tu empresa construya. -## Getting started +## Primeros pasos -Use the Angular CLI to generate a new library skeleton in a new workspace with the following commands. +Usa el Angular CLI para generar un nuevo esqueleto de librería en un nuevo espacio de trabajo con los siguientes comandos. @@ -17,26 +17,26 @@ ng generate library my-lib - + -You should be very careful when choosing the name of your library if you want to publish it later in a public package registry such as npm. -See [Publishing your library](tools/libraries/creating-libraries#publishing-your-library). +Debes tener mucho cuidado al elegir el nombre de tu librería si quieres publicarla más tarde en un registro de paquetes público como npm. +Consulta [Publicando tu librería](tools/libraries/creating-libraries#publishing-your-library). -Avoid using a name that is prefixed with `ng-`, such as `ng-library`. -The `ng-` prefix is a reserved keyword used from the Angular framework and its libraries. -The `ngx-` prefix is preferred as a convention used to denote that the library is suitable for use with Angular. -It is also an excellent indication to consumers of the registry to differentiate between libraries of different JavaScript frameworks. +Evita usar un nombre que esté prefijado con `ng-`, como `ng-library`. +El prefijo `ng-` es una palabra clave reservada usada por el framework Angular y sus librerías. +El prefijo `ngx-` se prefiere como una convención usada para denotar que la librería es adecuada para uso con Angular. +También es una excelente indicación para los consumidores del registro para diferenciar entre librerías de diferentes frameworks de JavaScript. -The `ng generate` command creates the `projects/my-lib` folder in your workspace, which contains a component. +El comando `ng generate` crea la carpeta `projects/my-lib` en tu espacio de trabajo, que contiene un componente. -HELPFUL: For more details on how a library project is structured, refer to the [Library project files](reference/configs/file-structure#library-project-files) section of the [Project File Structure guide](reference/configs/file-structure). +ÚTIL: Para más detalles sobre cómo se estructura un proyecto de librería, consulta la sección [Archivos de proyecto de librería](reference/configs/file-structure#library-project-files) de la [guía de Estructura de archivos del proyecto](reference/configs/file-structure). -Use the monorepo model to use the same workspace for multiple projects. -See [Setting up for a multi-project workspace](reference/configs/file-structure#multiple-projects). +Usa el modelo monorepo para usar el mismo espacio de trabajo para múltiples proyectos. +Consulta [Configurando un espacio de trabajo multi-proyecto](reference/configs/file-structure#multiple-projects). -When you generate a new library, the workspace configuration file, `angular.json`, is updated with a project of type `library`. +Cuando generas una nueva librería, el archivo de configuración del espacio de trabajo, `angular.json`, se actualiza con un proyecto de tipo `library`. @@ -54,7 +54,7 @@ When you generate a new library, the workspace configuration file, `angular.json -Build, test, and lint the project with CLI commands: +Construye, prueba y verifica el proyecto con comandos del CLI: @@ -64,80 +64,79 @@ ng lint my-lib -Notice that the configured builder for the project is different from the default builder for application projects. -This builder, among other things, ensures that the library is always built with the [AOT compiler](tools/cli/aot-compiler). +Observa que el builder configurado para el proyecto es diferente del builder predeterminado para proyectos de aplicación. +Este builder, entre otras cosas, asegura que la librería siempre se construya con el [compilador AOT](tools/cli/aot-compiler). -To make library code reusable you must define a public API for it. -This "user layer" defines what is available to consumers of your library. -A user of your library should be able to access public functionality \(such as service providers and general utility functions\) through a single import path. +Para hacer que el código de la librería sea reutilizable, debes definir una API pública para ella. +Esta "capa de usuario" define lo que está disponible para los consumidores de tu librería. +Un usuario de tu librería debería poder acceder a la funcionalidad pública \(como proveedores de servicios y funciones de utilidad generales\) a través de una única ruta de importación. -The public API for your library is maintained in the `public-api.ts` file in your library folder. -Anything exported from this file is made public when your library is imported into an application. +La API pública para tu librería se mantiene en el archivo `public-api.ts` en tu carpeta de librería. +Cualquier cosa exportada desde este archivo se hace pública cuando tu librería se importa en una aplicación. -Your library should supply documentation \(typically a README file\) for installation and maintenance. +Tu librería debería proporcionar documentación \(típicamente un archivo README\) para instalación y mantenimiento. -## Refactoring parts of an application into a library +## Refactorizando partes de una aplicación en una librería -To make your solution reusable, you need to adjust it so that it does not depend on application-specific code. -Here are some things to consider in migrating application functionality to a library. +Para hacer tu solución reutilizable, necesitas ajustarla para que no dependa de código específico de la aplicación. +Aquí hay algunas cosas a considerar al migrar funcionalidad de aplicación a una librería. -* Declarations such as components and pipes should be designed as stateless, meaning they don't rely on or alter external variables. - If you do rely on state, you need to evaluate every case and decide whether it is application state or state that the library would manage. +* Las declaraciones como componentes y pipes deberían diseñarse como sin estado, lo que significa que no dependen ni alteran variables externas. + Si dependes del estado, necesitas evaluar cada caso y decidir si es estado de aplicación o estado que la librería gestionaría. -* Any observables that the components subscribe to internally should be cleaned up and disposed of during the lifecycle of those components -* Components should expose their interactions through inputs for providing context, and outputs for communicating events to other components +* Cualquier observable al que los componentes se suscriban internamente debería limpiarse y eliminarse durante el ciclo de vida de esos componentes +* Los componentes deberían exponer sus interacciones a través de entradas para proporcionar contexto, y salidas para comunicar eventos a otros componentes -* Check all internal dependencies. - * For custom classes or interfaces used in components or service, check whether they depend on additional classes or interfaces that also need to be migrated - * Similarly, if your library code depends on a service, that service needs to be migrated - * If your library code or its templates depend on other libraries \(such as Angular Material, for instance\), you must configure your library with those dependencies +* Verifica todas las dependencias internas. + * Para clases personalizadas o interfaces usadas en componentes o servicios, verifica si dependen de clases o interfaces adicionales que también necesitan ser migradas + * De manera similar, si tu código de librería depende de un servicio, ese servicio necesita ser migrado + * Si tu código de librería o sus plantillas dependen de otras librerías \(como Angular Material, por ejemplo\), debes configurar tu librería con esas dependencias -* Consider how you provide services to client applications. +* Considera cómo proporcionas servicios a las aplicaciones cliente. - * Services should declare their own providers, rather than declaring providers in the NgModule or a component. - Declaring a provider makes that service *tree-shakable*. - This practice lets the compiler leave the service out of the bundle if it never gets injected into the application that imports the library. - For more about this, see [Tree-shakable providers](guide/di/lightweight-injection-tokens). + * Los servicios deberían declarar sus propios proveedores, en lugar de declarar proveedores en el NgModule o un componente. + Declarar un proveedor hace que ese servicio sea *tree-shakable*. + Esta práctica permite que el compilador deje el servicio fuera del bundle si nunca se inyecta en la aplicación que importa la librería. + Para más información sobre esto, consulta [Proveedores tree-shakable](guide/di/lightweight-injection-tokens). - * If you register global service providers expose a `provideXYZ()` provider function. - * If your library provides optional services that might not be used by all client applications, support proper tree-shaking for that case by using the [lightweight token design pattern](guide/di/lightweight-injection-tokens) + * Si registras proveedores de servicios globales, expone una función proveedor `provideXYZ()`. + * Si tu librería proporciona servicios opcionales que podrían no ser usados por todas las aplicaciones cliente, soporta tree-shaking apropiado para ese caso usando el [patrón de diseño de token ligero](guide/di/lightweight-injection-tokens) -## Integrating with the CLI using code-generation schematics +## Integración con el CLI usando schematics de generación de código -A library typically includes *reusable code* that defines components, services, and other Angular artifacts \(pipes, directives\) that you import into a project. -A library is packaged into an npm package for publishing and sharing. -This package can also include schematics that provide instructions for generating or transforming code directly in your project, in the same way that the CLI creates a generic new component with `ng generate component`. -A schematic that is packaged with a library can, for example, provide the Angular CLI with the information it needs to generate a component that configures and uses a particular feature, or set of features, defined in that library. -One example of this is [Angular Material's navigation schematic](https://material.angular.dev/guide/schematics#navigation-schematic) which configures the CDK's [BreakpointObserver](https://material.angular.dev/cdk/layout/overview#breakpointobserver) and uses it with Material's [MatSideNav](https://material.angular.dev/components/sidenav/overview) and [MatToolbar](https://material.angular.dev/components/toolbar/overview) components. +Una librería típicamente incluye *código reutilizable* que define componentes, servicios y otros artefactos de Angular \(pipes, directivas\) que importas en un proyecto. +Una librería se empaqueta en un paquete npm para publicación y distribución. +Este paquete también puede incluir schematics que proporcionan instrucciones para generar o transformar código directamente en tu proyecto, de la misma manera que el CLI crea un nuevo componente genérico con `ng generate component`. +Un schematic que se empaqueta con una librería puede, por ejemplo, proporcionar al Angular CLI la información que necesita para generar un componente que configure y use una característica particular, o conjunto de características, definidas en esa librería. +Un ejemplo de esto es el [schematic de navegación de Angular Material](https://material.angular.dev/guide/schematics#navigation-schematic) que configura el [BreakpointObserver](https://material.angular.dev/cdk/layout/overview#breakpointobserver) del CDK y lo usa con los componentes [MatSideNav](https://material.angular.dev/components/sidenav/overview) y [MatToolbar](https://material.angular.dev/components/toolbar/overview) de Material. -Create and include the following kinds of schematics: +Crea e incluye los siguientes tipos de schematics: -* Include an installation schematic so that `ng add` can add your library to a project -* Include generation schematics in your library so that `ng generate` can scaffold your defined artifacts \(components, services, tests\) in a project -* Include an update schematic so that `ng update` can update your library's dependencies and provide migrations for breaking changes in new releases +* Incluye un schematic de instalación para que `ng add` pueda agregar tu librería a un proyecto +* Incluye schematics de generación en tu librería para que `ng generate` pueda crear tus artefactos definidos \(componentes, servicios, pruebas\) en un proyecto +* Incluye un schematic de actualización para que `ng update` pueda actualizar las dependencias de tu librería y proporcionar migraciones para cambios disruptivos en nuevas versiones -What you include in your library depends on your task. -For example, you could define a schematic to create a dropdown that is pre-populated with canned data to show how to add it to an application. -If you want a dropdown that would contain different passed-in values each time, your library could define a schematic to create it with a given configuration. -Developers could then use `ng generate` to configure an instance for their own application. +Lo que incluyas en tu librería depende de tu tarea. +Por ejemplo, podrías definir un schematic para crear un dropdown que esté pre-poblado con datos predefinidos para mostrar cómo agregarlo a una aplicación. +Si quieres un dropdown que contenga diferentes valores pasados cada vez, tu librería podría definir un schematic para crearlo con una configuración dada. +Los desarrolladores podrían entonces usar `ng generate` para configurar una instancia para su propia aplicación. -Suppose you want to read a configuration file and then generate a form based on that configuration. -If that form needs additional customization by the developer who is using your library, it might work best as a schematic. -However, if the form will always be the same and not need much customization by developers, then you could create a dynamic component that takes the configuration and generates the form. -In general, the more complex the customization, the more useful the schematic approach. +Supón que quieres leer un archivo de configuración y luego generar un formulario basado en esa configuración. +Si ese formulario necesita personalización adicional por parte del desarrollador que está usando tu librería, podría funcionar mejor como un schematic. +Sin embargo, si el formulario siempre será el mismo y no necesitará mucha personalización por parte de los desarrolladores, entonces podrías crear un componente dinámico que tome la configuración y genere el formulario. +En general, cuanto más compleja sea la personalización, más útil será el enfoque de schematic. -For more information, see [Schematics Overview](tools/cli/schematics) and [Schematics for Libraries](tools/cli/schematics-for-libraries). +Para más información, consulta [Visión general de Schematics](tools/cli/schematics) y [Schematics para librerías](tools/cli/schematics-for-libraries). -## Publishing your library +## Publicando tu librería -Use the Angular CLI and the npm package manager to build and publish your library as an npm package. +Usa el Angular CLI y el gestor de paquetes npm para construir y publicar tu librería como un paquete npm. -Angular CLI uses a tool called [ng-packagr](https://github.com/ng-packagr/ng-packagr/blob/master/README.md) to create packages from your compiled code that can be published to npm. -See [Building libraries with Ivy](tools/libraries/creating-libraries#publishing-libraries) for information on the distribution formats supported by `ng-packagr` and guidance on how -to choose the right format for your library. +Angular CLI usa una herramienta llamada [ng-packagr](https://github.com/ng-packagr/ng-packagr/blob/master/README.md) para crear paquetes desde tu código compilado que pueden publicarse en npm. +Consulta [Construyendo librerías con Ivy](tools/libraries/creating-libraries#publishing-libraries) para información sobre los formatos de distribución soportados por `ng-packagr` y orientación sobre cómo elegir el formato correcto para tu librería. -You should always build libraries for distribution using the `production` configuration. -This ensures that generated output uses the appropriate optimizations and the correct package format for npm. +Siempre debes construir librerías para distribución usando la configuración `production`. +Esto asegura que la salida generada use las optimizaciones apropiadas y el formato de paquete correcto para npm. @@ -147,15 +146,15 @@ npm publish -## Managing assets in a library +## Gestionando recursos en una librería -In your Angular library, the distributable can include additional assets like theming files, Sass mixins, or documentation \(like a changelog\). -For more information [copy assets into your library as part of the build](https://github.com/ng-packagr/ng-packagr/blob/master/docs/copy-assets.md) and [embed assets in component styles](https://github.com/ng-packagr/ng-packagr/blob/master/docs/embed-assets-css.md). +En tu librería de Angular, el distribuible puede incluir recursos adicionales como archivos de temas, mixins de Sass, o documentación \(como un changelog\). +Para más información [copia recursos en tu librería como parte de la compilación](https://github.com/ng-packagr/ng-packagr/blob/master/docs/copy-assets.md) e [incrusta recursos en estilos de componentes](https://github.com/ng-packagr/ng-packagr/blob/master/docs/embed-assets-css.md). -IMPORTANT: When including additional assets like Sass mixins or pre-compiled CSS. -You need to add these manually to the conditional ["exports"](tools/libraries/angular-package-format#quotexportsquot) in the `package.json` of the primary entrypoint. +IMPORTANTE: Cuando incluyas recursos adicionales como mixins de Sass o CSS pre-compilado. +Necesitas agregar estos manualmente a las ["exports"](tools/libraries/angular-package-format#quotexportsquot) condicionales en el `package.json` del punto de entrada principal. -`ng-packagr` will merge handwritten `"exports"` with the auto-generated ones, allowing for library authors to configure additional export subpaths, or custom conditions. +`ng-packagr` fusionará las `"exports"` escritas manualmente con las auto-generadas, permitiendo que los autores de librerías configuren subpaths de exportación adicionales, o condiciones personalizadas. @@ -173,22 +172,22 @@ You need to add these manually to the conditional ["exports"](tools/libraries/an -The above is an extract from the [@angular/material](https://unpkg.com/browse/@angular/material/package.json) distributable. +Lo anterior es un extracto del distribuible de [@angular/material](https://unpkg.com/browse/@angular/material/package.json). -## Peer dependencies +## Dependencias peer -Angular libraries should list any `@angular/*` dependencies the library depends on as peer dependencies. -This ensures that when modules ask for Angular, they all get the exact same module. -If a library lists `@angular/core` in `dependencies` instead of `peerDependencies`, it might get a different Angular module instead, which would cause your application to break. +Las librerías de Angular deberían listar cualquier dependencia `@angular/*` de la que dependa la librería como dependencias peer. +Esto asegura que cuando los módulos pidan Angular, todos obtengan exactamente el mismo módulo. +Si una librería lista `@angular/core` en `dependencies` en lugar de `peerDependencies`, podría obtener un módulo Angular diferente, lo que causaría que tu aplicación falle. -## Using your own library in applications +## Usando tu propia librería en aplicaciones -You don't have to publish your library to the npm package manager to use it in the same workspace, but you do have to build it first. +No tienes que publicar tu librería en el gestor de paquetes npm para usarla en el mismo espacio de trabajo, pero sí tienes que construirla primero. -To use your own library in an application: +Para usar tu propia librería en una aplicación: -* Build the library. - You cannot use a library before it is built. +* Construye la librería. + No puedes usar una librería antes de que se construya. @@ -196,7 +195,7 @@ To use your own library in an application: -* In your applications, import from the library by name: +* En tus aplicaciones, importa desde la librería por nombre: @@ -204,28 +203,28 @@ To use your own library in an application: -### Building and rebuilding your library +### Construyendo y reconstruyendo tu librería -The build step is important if you haven't published your library as an npm package and then installed the package back into your application from npm. -For instance, if you clone your git repository and run `npm install`, your editor shows the `my-lib` imports as missing if you haven't yet built your library. +El paso de construcción es importante si no has publicado tu librería como un paquete npm y luego instalado el paquete de vuelta en tu aplicación desde npm. +Por ejemplo, si clonas tu repositorio git y ejecutas `npm install`, tu editor muestra las importaciones de `my-lib` como faltantes si aún no has construido tu librería. -HELPFUL: When you import something from a library in an Angular application, Angular looks for a mapping between the library name and a location on disk. -When you install a library package, the mapping is in the `node_modules` folder. -When you build your own library, it has to find the mapping in your `tsconfig` paths. +ÚTIL: Cuando importas algo desde una librería en una aplicación de Angular, Angular busca un mapeo entre el nombre de la librería y una ubicación en disco. +Cuando instalas un paquete de librería, el mapeo está en la carpeta `node_modules`. +Cuando construyes tu propia librería, tiene que encontrar el mapeo en tus rutas `tsconfig`. -Generating a library with the Angular CLI automatically adds its path to the `tsconfig` file. -The Angular CLI uses the `tsconfig` paths to tell the build system where to find the library. +Generar una librería con el Angular CLI agrega automáticamente su ruta al archivo `tsconfig`. +El Angular CLI usa las rutas `tsconfig` para decirle al sistema de compilación dónde encontrar la librería. -For more information, see [Path mapping overview](https://www.typescriptlang.org/docs/handbook/module-resolution.html#path-mapping). +Para más información, consulta [Visión general del mapeo de rutas](https://www.typescriptlang.org/docs/handbook/module-resolution.html#path-mapping). -If you find that changes to your library are not reflected in your application, your application is probably using an old build of the library. +Si encuentras que los cambios en tu librería no se reflejan en tu aplicación, tu aplicación probablemente esté usando una construcción antigua de la librería. -You can rebuild your library whenever you make changes to it, but this extra step takes time. -*Incremental builds* functionality improves the library-development experience. -Every time a file is changed a partial build is performed that emits the amended files. +Puedes reconstruir tu librería cuando hagas cambios en ella, pero este paso extra lleva tiempo. +La funcionalidad de *compilaciones incrementales* mejora la experiencia de desarrollo de librerías. +Cada vez que se cambia un archivo, se realiza una compilación parcial que emite los archivos modificados. -Incremental builds can be run as a background process in your development environment. -To take advantage of this feature add the `--watch` flag to the build command: +Las compilaciones incrementales pueden ejecutarse como un proceso en segundo plano en tu entorno de desarrollo. +Para aprovechar esta característica, agrega la bandera `--watch` al comando de compilación: @@ -233,59 +232,59 @@ ng build my-lib --watch -IMPORTANT: The CLI `build` command uses a different builder and invokes a different build tool for libraries than it does for applications. +IMPORTANTE: El comando `build` del CLI usa un builder diferente e invoca una herramienta de compilación diferente para librerías que para aplicaciones. -* The build system for applications, `@angular-devkit/build-angular`, is based on `webpack`, and is included in all new Angular CLI projects -* The build system for libraries is based on `ng-packagr`. - It is only added to your dependencies when you add a library using `ng generate library my-lib`. +* El sistema de compilación para aplicaciones, `@angular-devkit/build-angular`, está basado en `webpack`, y está incluido en todos los nuevos proyectos de Angular CLI +* El sistema de compilación para librerías está basado en `ng-packagr`. + Solo se agrega a tus dependencias cuando agregas una librería usando `ng generate library my-lib`. -The two build systems support different things, and even where they support the same things, they do those things differently. -This means that the TypeScript source can result in different JavaScript code in a built library than it would in a built application. +Los dos sistemas de compilación soportan cosas diferentes, e incluso donde soportan las mismas cosas, hacen esas cosas de manera diferente. +Esto significa que el código fuente TypeScript puede resultar en código JavaScript diferente en una librería construida que en una aplicación construida. -For this reason, an application that depends on a library should only use TypeScript path mappings that point to the *built library*. -TypeScript path mappings should *not* point to the library source `.ts` files. +Por esta razón, una aplicación que depende de una librería debería usar solo mapeos de rutas de TypeScript que apunten a la *librería construida*. +Los mapeos de rutas de TypeScript *no* deberían apuntar a los archivos `.ts` fuente de la librería. -## Publishing libraries +## Publicando librerías -There are two distribution formats to use when publishing a library: +Hay dos formatos de distribución para usar al publicar una librería: -| Distribution formats | Details | -|:--- |:--- | -| Partial-Ivy \(recommended\) | Contains portable code that can be consumed by Ivy applications built with any version of Angular from v12 onwards. | -| Full-Ivy | Contains private Angular Ivy instructions, which are not guaranteed to work across different versions of Angular. This format requires that the library and application are built with the *exact* same version of Angular. This format is useful for environments where all library and application code is built directly from source. | +| Formatos de distribución | Detalles | +|:--- |:--- | +| Partial-Ivy \(recomendado\) | Contiene código portable que puede ser consumido por aplicaciones Ivy construidas con cualquier versión de Angular desde v12 en adelante. | +| Full-Ivy | Contiene instrucciones privadas de Angular Ivy, que no están garantizadas para funcionar en diferentes versiones de Angular. Este formato requiere que la librería y la aplicación sean construidas con la *misma* versión exacta de Angular. Este formato es útil para entornos donde todo el código de librería y aplicación se construye directamente desde el código fuente. | -For publishing to npm use the partial-Ivy format as it is stable between patch versions of Angular. +Para publicar en npm usa el formato partial-Ivy ya que es estable entre versiones de parche de Angular. -Avoid compiling libraries with full-Ivy code if you are publishing to npm because the generated Ivy instructions are not part of Angular's public API, and so might change between patch versions. +Evita compilar librerías con código full-Ivy si estás publicando en npm porque las instrucciones Ivy generadas no son parte de la API pública de Angular, y por lo tanto podrían cambiar entre versiones de parche. -## Ensuring library version compatibility +## Asegurando compatibilidad de versión de librería -The Angular version used to build an application should always be the same or greater than the Angular versions used to build any of its dependent libraries. -For example, if you had a library using Angular version 13, the application that depends on that library should use Angular version 13 or later. -Angular does not support using an earlier version for the application. +La versión de Angular usada para construir una aplicación siempre debería ser la misma o mayor que las versiones de Angular usadas para construir cualquiera de sus librerías dependientes. +Por ejemplo, si tuvieras una librería usando Angular versión 13, la aplicación que depende de esa librería debería usar Angular versión 13 o posterior. +Angular no soporta usar una versión anterior para la aplicación. -If you intend to publish your library to npm, compile with partial-Ivy code by setting `"compilationMode": "partial"` in `tsconfig.prod.json`. -This partial format is stable between different versions of Angular, so is safe to publish to npm. -Code with this format is processed during the application build using the same version of the Angular compiler, ensuring that the application and all of its libraries use a single version of Angular. +Si tienes la intención de publicar tu librería en npm, compila con código partial-Ivy estableciendo `"compilationMode": "partial"` en `tsconfig.prod.json`. +Este formato parcial es estable entre diferentes versiones de Angular, por lo que es seguro publicar en npm. +El código con este formato se procesa durante la compilación de la aplicación usando la misma versión del compilador de Angular, asegurando que la aplicación y todas sus librerías usen una única versión de Angular. -Avoid compiling libraries with full-Ivy code if you are publishing to npm because the generated Ivy instructions are not part of Angular's public API, and so might change between patch versions. +Evita compilar librerías con código full-Ivy si estás publicando en npm porque las instrucciones Ivy generadas no son parte de la API pública de Angular, y por lo tanto podrían cambiar entre versiones de parche. -If you've never published a package in npm before, you must create a user account. -Read more in [Publishing npm Packages](https://docs.npmjs.com/getting-started/publishing-npm-packages). +Si nunca has publicado un paquete en npm antes, debes crear una cuenta de usuario. +Lee más en [Publicando paquetes npm](https://docs.npmjs.com/getting-started/publishing-npm-packages). -## Consuming partial-Ivy code outside the Angular CLI +## Consumiendo código partial-Ivy fuera del Angular CLI -An application installs many Angular libraries from npm into its `node_modules` directory. -However, the code in these libraries cannot be bundled directly along with the built application as it is not fully compiled. -To finish compilation, use the Angular linker. +Una aplicación instala muchas librerías de Angular desde npm en su directorio `node_modules`. +Sin embargo, el código en estas librerías no puede empaquetarse directamente junto con la aplicación construida ya que no está completamente compilado. +Para terminar la compilación, usa el linker de Angular. -For applications that don't use the Angular CLI, the linker is available as a [Babel](https://babeljs.io) plugin. -The plugin is to be imported from `@angular/compiler-cli/linker/babel`. +Para aplicaciones que no usan el Angular CLI, el linker está disponible como un plugin de [Babel](https://babeljs.io). +El plugin debe importarse desde `@angular/compiler-cli/linker/babel`. -The Angular linker Babel plugin supports build caching, meaning that libraries only need to be processed by the linker a single time, regardless of other npm operations. +El plugin Babel del linker de Angular soporta caché de compilación, lo que significa que las librerías solo necesitan ser procesadas por el linker una sola vez, independientemente de otras operaciones de npm. -Example of integrating the plugin into a custom [webpack](https://webpack.js.org) build by registering the linker as a [Babel](https://babeljs.io) plugin using [babel-loader](https://webpack.js.org/loaders/babel-loader/#options). +Ejemplo de integración del plugin en una compilación personalizada de [webpack](https://webpack.js.org) registrando el linker como un plugin de [Babel](https://babeljs.io) usando [babel-loader](https://webpack.js.org/loaders/babel-loader/#options). -HELPFUL: The Angular CLI integrates the linker plugin automatically, so if consumers of your library are using the CLI, they can install Ivy-native libraries from npm without any additional configuration. +ÚTIL: El Angular CLI integra el plugin linker automáticamente, así que si los consumidores de tu librería están usando el CLI, pueden instalar librerías nativas de Ivy desde npm sin ninguna configuración adicional. diff --git a/adev-es/src/content/tools/libraries/overview.en.md b/adev-es/src/content/tools/libraries/overview.en.md new file mode 100644 index 0000000..99be388 --- /dev/null +++ b/adev-es/src/content/tools/libraries/overview.en.md @@ -0,0 +1,34 @@ +# Overview of Angular libraries + +Many applications need to solve the same general problems, such as presenting a unified user interface, presenting data, and allowing data entry. +Developers can create general solutions for particular domains that can be adapted for re-use in different applications. +Such a solution can be built as Angular *libraries* and these libraries can be published and shared as *npm packages*. + +An Angular library is an Angular project that differs from an application in that it cannot run on its own. +A library must be imported and used in an application. + +Libraries extend Angular's base features. +For example, to add [reactive forms](guide/forms/reactive-forms) to an application, add the library package using `ng add @angular/forms`, then import the `ReactiveFormsModule` from the `@angular/forms` library in your application code. +Similarly, adding the [service worker](ecosystem/service-workers) library to an Angular application is one of the steps for turning an application into a [Progressive Web App](https://developers.google.com/web/progressive-web-apps) \(PWA\). +[Angular Material](https://material.angular.dev) is an example of a large, general-purpose library that provides sophisticated, reusable, and adaptable UI components. + +Any application developer can use these and other libraries that have been published as npm packages by the Angular team or by third parties. +See [Using Published Libraries](tools/libraries/using-libraries). + +HELPFUL: Libraries are intended to be used by Angular applications. To add Angular features to non-Angular web applications, use [Angular custom elements](guide/elements). + +## Creating libraries + +If you have developed features that are suitable for reuse, you can create your own libraries. +These libraries can be used locally in your workspace, or you can publish them as [npm packages](reference/configs/npm-packages) to share with other projects or other Angular developers. +These packages can be published to the npm registry, a private npm Enterprise registry, or a private package management system that supports npm packages. +See [Creating Libraries](tools/libraries/creating-libraries). + +Deciding to package features as a library is an architectural decision. It is comparable to deciding whether a feature is a component or a service, or deciding on the scope of a component. + +Packaging features as a library forces the artifacts in the library to be decoupled from the application's business logic. +This can help to avoid various bad practices or architecture mistakes that can make it difficult to decouple and reuse code in the future. + +Putting code into a separate library is more complex than simply putting everything in one application. +It requires more of an investment in time and thought for managing, maintaining, and updating the library. +This complexity can pay off when the library is being used in multiple applications. diff --git a/adev-es/src/content/tools/libraries/overview.md b/adev-es/src/content/tools/libraries/overview.md index 99be388..c865ba1 100644 --- a/adev-es/src/content/tools/libraries/overview.md +++ b/adev-es/src/content/tools/libraries/overview.md @@ -1,34 +1,34 @@ -# Overview of Angular libraries +# Visión general de las librerías de Angular -Many applications need to solve the same general problems, such as presenting a unified user interface, presenting data, and allowing data entry. -Developers can create general solutions for particular domains that can be adapted for re-use in different applications. -Such a solution can be built as Angular *libraries* and these libraries can be published and shared as *npm packages*. +Muchas aplicaciones necesitan resolver los mismos problemas generales, como presentar una interfaz de usuario unificada, presentar datos y permitir la entrada de datos. +Los desarrolladores pueden crear soluciones generales para dominios particulares que pueden ser adaptadas para reutilización en diferentes aplicaciones. +Tales soluciones pueden construirse como *librerías* de Angular y estas librerías pueden publicarse y compartirse como *paquetes npm*. -An Angular library is an Angular project that differs from an application in that it cannot run on its own. -A library must be imported and used in an application. +Una librería de Angular es un proyecto de Angular que difiere de una aplicación en que no puede ejecutarse por sí sola. +Una librería debe importarse y usarse en una aplicación. -Libraries extend Angular's base features. -For example, to add [reactive forms](guide/forms/reactive-forms) to an application, add the library package using `ng add @angular/forms`, then import the `ReactiveFormsModule` from the `@angular/forms` library in your application code. -Similarly, adding the [service worker](ecosystem/service-workers) library to an Angular application is one of the steps for turning an application into a [Progressive Web App](https://developers.google.com/web/progressive-web-apps) \(PWA\). -[Angular Material](https://material.angular.dev) is an example of a large, general-purpose library that provides sophisticated, reusable, and adaptable UI components. +Las librerías extienden las características base de Angular. +Por ejemplo, para agregar [formularios reactivos](guide/forms/reactive-forms) a una aplicación, agrega el paquete de la librería usando `ng add @angular/forms`, luego importa el `ReactiveFormsModule` desde la librería `@angular/forms` en el código de tu aplicación. +De manera similar, agregar la librería de [service worker](ecosystem/service-workers) a una aplicación de Angular es uno de los pasos para convertir una aplicación en una [Aplicación Web Progresiva](https://developers.google.com/web/progressive-web-apps) \(PWA\). +[Angular Material](https://material.angular.dev) es un ejemplo de una librería grande y de propósito general que proporciona componentes de interfaz de usuario sofisticados, reutilizables y adaptables. -Any application developer can use these and other libraries that have been published as npm packages by the Angular team or by third parties. -See [Using Published Libraries](tools/libraries/using-libraries). +Cualquier desarrollador de aplicaciones puede usar estas y otras librerías que han sido publicadas como paquetes npm por el equipo de Angular o por terceros. +Consulta [Usando librerías publicadas](tools/libraries/using-libraries). -HELPFUL: Libraries are intended to be used by Angular applications. To add Angular features to non-Angular web applications, use [Angular custom elements](guide/elements). +ÚTIL: Las librerías están destinadas a ser usadas por aplicaciones de Angular. Para agregar características de Angular a aplicaciones web que no son Angular, usa [elementos personalizados de Angular](guide/elements). -## Creating libraries +## Creando librerías -If you have developed features that are suitable for reuse, you can create your own libraries. -These libraries can be used locally in your workspace, or you can publish them as [npm packages](reference/configs/npm-packages) to share with other projects or other Angular developers. -These packages can be published to the npm registry, a private npm Enterprise registry, or a private package management system that supports npm packages. -See [Creating Libraries](tools/libraries/creating-libraries). +Si has desarrollado características que son adecuadas para reutilización, puedes crear tus propias librerías. +Estas librerías pueden usarse localmente en tu espacio de trabajo, o puedes publicarlas como [paquetes npm](reference/configs/npm-packages) para compartirlas con otros proyectos u otros desarrolladores de Angular. +Estos paquetes pueden publicarse en el registro de npm, un registro privado de npm Enterprise, o un sistema privado de gestión de paquetes que soporte paquetes npm. +Consulta [Creando librerías](tools/libraries/creating-libraries). -Deciding to package features as a library is an architectural decision. It is comparable to deciding whether a feature is a component or a service, or deciding on the scope of a component. +Decidir empaquetar características como una librería es una decisión arquitectónica. Es comparable a decidir si una característica es un componente o un servicio, o decidir el alcance de un componente. -Packaging features as a library forces the artifacts in the library to be decoupled from the application's business logic. -This can help to avoid various bad practices or architecture mistakes that can make it difficult to decouple and reuse code in the future. +Empaquetar características como una librería fuerza a que los artefactos en la librería estén desacoplados de la lógica de negocio de la aplicación. +Esto puede ayudar a evitar varias malas prácticas o errores arquitectónicos que pueden dificultar el desacoplamiento y reutilización del código en el futuro. -Putting code into a separate library is more complex than simply putting everything in one application. -It requires more of an investment in time and thought for managing, maintaining, and updating the library. -This complexity can pay off when the library is being used in multiple applications. +Poner código en una librería separada es más complejo que simplemente poner todo en una aplicación. +Requiere más inversión en tiempo y reflexión para gestionar, mantener y actualizar la librería. +Esta complejidad puede valer la pena cuando la librería está siendo usada en múltiples aplicaciones. diff --git a/adev-es/src/content/tools/libraries/using-libraries.en.md b/adev-es/src/content/tools/libraries/using-libraries.en.md new file mode 100644 index 0000000..777add5 --- /dev/null +++ b/adev-es/src/content/tools/libraries/using-libraries.en.md @@ -0,0 +1,195 @@ +# Usage of Angular libraries published to npm + +When you build your Angular application, take advantage of sophisticated first-party libraries, as well as a rich ecosystem of third-party libraries. +[Angular Material][AngularMaterialMain] is an example of a sophisticated first-party library. + +## Install libraries + +Libraries are published as [npm packages][GuideNpmPackages], usually together with schematics that integrate them with the Angular CLI. +To integrate reusable library code into an application, you need to install the package and import the provided functionality in the location you use it. +For most published Angular libraries, use the `ng add ` Angular CLI command. + +The `ng add` Angular CLI command uses a package manager to install the library package and invokes schematics that are included in the package to other scaffolding within the project code. +Examples of package managers include [npm][NpmjsMain] or [yarn][YarnpkgMain]. +Additional scaffolding within the project code includes import statements, fonts, and themes. + +A published library typically provides a `README` file or other documentation on how to add that library to your application. +For an example, see the [Angular Material][AngularMaterialMain] documentation. + +### Library typings + +Typically, library packages include typings in `.d.ts` files; see examples in `node_modules/@angular/material`. +If the package of your library does not include typings and your IDE complains, you might need to install the `@types/` package with the library. + +For example, suppose you have a library named `d3`: + + + +npm install d3 --save +npm install @types/d3 --save-dev + + + +Types defined in a `@types/` package for a library installed into the workspace are automatically added to the TypeScript configuration for the project that uses that library. +TypeScript looks for types in the `node_modules/@types` directory by default, so you do not have to add each type package individually. + +If a library does not have typings available at `@types/`, you may use it by manually adding typings for it. +To do this: + +1. Create a `typings.d.ts` file in your `src/` directory. + This file is automatically included as global type definition. + +1. Add the following code in `src/typings.d.ts`: + + + + declare module 'host' { + export interface Host { + protocol?: string; + hostname?: string; + pathname?: string; + } + export function parse(url: string, queryString?: string): Host; + } + + + +1. In the component or file that uses the library, add the following code: + + + + import * as host from 'host'; + const parsedUrl = host.parse('https://angular.dev'); + console.log(parsedUrl.hostname); + + + +Define more typings as needed. + +## Updating libraries + +A library is able to be updated by the publisher, and also has individual dependencies which need to be kept current. +To check for updates to your installed libraries, use the [`ng update`][CliUpdate] Angular CLI command. + +Use `ng update ` Angular CLI command to update individual library versions. +The Angular CLI checks the latest published release of the library, and if the latest version is newer than your installed version, downloads it and updates your `package.json` to match the latest version. + +When you update Angular to a new version, you need to make sure that any libraries you are using are current. +If libraries have interdependencies, you might have to update them in a particular order. +See the [Angular Update Guide][AngularUpdateMain] for help. + +## Adding a library to the runtime global scope + +If a legacy JavaScript library is not imported into an application, you may add it to the runtime global scope and load it as if it was added in a script tag. +Configure the Angular CLI to do this at build time using the `scripts` and `styles` options of the build target in the [`angular.json`][GuideWorkspaceConfig] workspace build configuration file. + +For example, to use the [Bootstrap 4][GetbootstrapDocs40GettingStartedIntroduction] library + +1. Install the library and the associated dependencies using the npm package manager: + + + + npm install jquery --save + npm install popper.js --save + npm install bootstrap --save + + + +1. In the `angular.json` configuration file, add the associated script files to the `scripts` array: + + + + "scripts": [ + "node_modules/jquery/dist/jquery.slim.js", + "node_modules/popper.js/dist/umd/popper.js", + "node_modules/bootstrap/dist/js/bootstrap.js" + ], + + + +1. Add the `bootstrap.css` CSS file to the `styles` array: + + + + "styles": [ + "node_modules/bootstrap/dist/css/bootstrap.css", + "src/styles.css" + ], + + + +1. Run or restart the `ng serve` Angular CLI command to see Bootstrap 4 work in your application. + +### Using runtime-global libraries inside your app + +After you import a library using the "scripts" array, do **not** import it using an import statement in your TypeScript code. +The following code snippet is an example import statement. + + + +import * as $ from 'jquery'; + + + +If you import it using import statements, you have two different copies of the library: one imported as a global library, and one imported as a module. +This is especially bad for libraries with plugins, like JQuery, because each copy includes different plugins. + +Instead, run the `npm install @types/jquery` Angular CLI command to download typings for your library and then follow the library installation steps. +This gives you access to the global variables exposed by that library. + +### Defining typings for runtime-global libraries + +If the global library you need to use does not have global typings, you can declare them manually as `any` in `src/typings.d.ts`. + +For example: + + + +declare var libraryName: any; + + + +Some scripts extend other libraries; for instance with JQuery plugins: + + + +$('.test').myPlugin(); + + + +In this case, the installed `@types/jquery` does not include `myPlugin`, so you need to add an interface in `src/typings.d.ts`. +For example: + + + +interface JQuery { + myPlugin(options?: any): any; +} + + + +If you do not add the interface for the script-defined extension, your IDE shows an error: + + + +[TS][Error] Property 'myPlugin' does not exist on type 'JQuery' + + + +[CliUpdate]: cli/update "ng update | CLI |Angular" + +[GuideNpmPackages]: reference/configs/npm-packages "Workspace npm dependencies | Angular" + +[GuideWorkspaceConfig]: reference/configs/workspace-config "Angular workspace configuration | Angular" + +[Resources]: resources "Explore Angular Resources | Angular" + +[AngularMaterialMain]: https://material.angular.dev "Angular Material | Angular" + +[AngularUpdateMain]: https://angular.dev/update-guide "Angular Update Guide | Angular" + +[GetbootstrapDocs40GettingStartedIntroduction]: https://getbootstrap.com/docs/4.0/getting-started/introduction "Introduction | Bootstrap" + +[NpmjsMain]: https://www.npmjs.com "npm" + +[YarnpkgMain]: https://yarnpkg.com " Yarn" diff --git a/adev-es/src/content/tools/libraries/using-libraries.md b/adev-es/src/content/tools/libraries/using-libraries.md index 777add5..7678cd0 100644 --- a/adev-es/src/content/tools/libraries/using-libraries.md +++ b/adev-es/src/content/tools/libraries/using-libraries.md @@ -1,27 +1,27 @@ -# Usage of Angular libraries published to npm +# Uso de librerías de Angular publicadas en npm -When you build your Angular application, take advantage of sophisticated first-party libraries, as well as a rich ecosystem of third-party libraries. -[Angular Material][AngularMaterialMain] is an example of a sophisticated first-party library. +Cuando construyes tu aplicación de Angular, aprovecha las sofisticadas librerías propias, así como un ecosistema rico de librerías de terceros. +[Angular Material][AngularMaterialMain] es un ejemplo de una librería propia sofisticada. -## Install libraries +## Instalar librerías -Libraries are published as [npm packages][GuideNpmPackages], usually together with schematics that integrate them with the Angular CLI. -To integrate reusable library code into an application, you need to install the package and import the provided functionality in the location you use it. -For most published Angular libraries, use the `ng add ` Angular CLI command. +Las librerías se publican como [paquetes npm][GuideNpmPackages], generalmente junto con schematics que las integran con el Angular CLI. +Para integrar código de librería reutilizable en una aplicación, necesitas instalar el paquete e importar la funcionalidad proporcionada en la ubicación donde la uses. +Para la mayoría de las librerías publicadas de Angular, usa el comando `ng add ` de Angular CLI. -The `ng add` Angular CLI command uses a package manager to install the library package and invokes schematics that are included in the package to other scaffolding within the project code. -Examples of package managers include [npm][NpmjsMain] or [yarn][YarnpkgMain]. -Additional scaffolding within the project code includes import statements, fonts, and themes. +El comando `ng add` de Angular CLI usa un gestor de paquetes para instalar el paquete de la librería e invoca schematics que están incluidos en el paquete para generar scaffold adicional dentro del código del proyecto. +Ejemplos de gestores de paquetes incluyen [npm][NpmjsMain] o [yarn][YarnpkgMain]. +El scaffold adicional dentro del código del proyecto incluye declaraciones de importación, fuentes y temas. -A published library typically provides a `README` file or other documentation on how to add that library to your application. -For an example, see the [Angular Material][AngularMaterialMain] documentation. +Una librería publicada típicamente proporciona un archivo `README` u otra documentación sobre cómo agregar esa librería a tu aplicación. +Para un ejemplo, consulta la documentación de [Angular Material][AngularMaterialMain]. -### Library typings +### Tipado de librerías -Typically, library packages include typings in `.d.ts` files; see examples in `node_modules/@angular/material`. -If the package of your library does not include typings and your IDE complains, you might need to install the `@types/` package with the library. +Típicamente, los paquetes de librerías incluyen tipados en archivos `.d.ts`; consulta ejemplos en `node_modules/@angular/material`. +Si el paquete de tu librería no incluye tipados y tu IDE se queja, es posible que necesites instalar el paquete `@types/` con la librería. -For example, suppose you have a library named `d3`: +Por ejemplo, supón que tienes una librería llamada `d3`: @@ -30,16 +30,16 @@ npm install @types/d3 --save-dev -Types defined in a `@types/` package for a library installed into the workspace are automatically added to the TypeScript configuration for the project that uses that library. -TypeScript looks for types in the `node_modules/@types` directory by default, so you do not have to add each type package individually. +Los tipos definidos en un paquete `@types/` para una librería instalada en el espacio de trabajo se agregan automáticamente a la configuración de TypeScript para el proyecto que usa esa librería. +TypeScript busca tipos en el directorio `node_modules/@types` por defecto, así que no tienes que agregar cada paquete de tipos individualmente. -If a library does not have typings available at `@types/`, you may use it by manually adding typings for it. -To do this: +Si una librería no tiene tipados disponibles en `@types/`, puedes usarla agregando manualmente tipados para ella. +Para hacer esto: -1. Create a `typings.d.ts` file in your `src/` directory. - This file is automatically included as global type definition. +1. Crea un archivo `typings.d.ts` en tu directorio `src/`. + Este archivo se incluye automáticamente como definición de tipo global. -1. Add the following code in `src/typings.d.ts`: +1. Agrega el siguiente código en `src/typings.d.ts`: @@ -54,7 +54,7 @@ To do this: -1. In the component or file that uses the library, add the following code: +1. En el componente o archivo que usa la librería, agrega el siguiente código: @@ -64,28 +64,28 @@ To do this: -Define more typings as needed. +Define más tipados según sea necesario. -## Updating libraries +## Actualizar librerías -A library is able to be updated by the publisher, and also has individual dependencies which need to be kept current. -To check for updates to your installed libraries, use the [`ng update`][CliUpdate] Angular CLI command. +Una librería puede ser actualizada por el publicador, y también tiene dependencias individuales que necesitan mantenerse actualizadas. +Para verificar actualizaciones de tus librerías instaladas, usa el comando [`ng update`][CliUpdate] de Angular CLI. -Use `ng update ` Angular CLI command to update individual library versions. -The Angular CLI checks the latest published release of the library, and if the latest version is newer than your installed version, downloads it and updates your `package.json` to match the latest version. +Usa el comando `ng update ` de Angular CLI para actualizar versiones individuales de librerías. +El Angular CLI verifica la última versión publicada de la librería, y si la última versión es más reciente que tu versión instalada, la descarga y actualiza tu `package.json` para que coincida con la última versión. -When you update Angular to a new version, you need to make sure that any libraries you are using are current. -If libraries have interdependencies, you might have to update them in a particular order. -See the [Angular Update Guide][AngularUpdateMain] for help. +Cuando actualizas Angular a una nueva versión, necesitas asegurarte de que cualquier librería que estés usando esté actualizada. +Si las librerías tienen interdependencias, es posible que tengas que actualizarlas en un orden particular. +Consulta la [Guía de actualización de Angular][AngularUpdateMain] para obtener ayuda. -## Adding a library to the runtime global scope +## Agregar una librería al alcance global en tiempo de ejecución -If a legacy JavaScript library is not imported into an application, you may add it to the runtime global scope and load it as if it was added in a script tag. -Configure the Angular CLI to do this at build time using the `scripts` and `styles` options of the build target in the [`angular.json`][GuideWorkspaceConfig] workspace build configuration file. +Si una librería heredada de JavaScript no se importa en una aplicación, puedes agregarla al alcance global en tiempo de ejecución y cargarla como si se hubiera agregado en una etiqueta script. +Configura el Angular CLI para hacer esto en tiempo de compilación usando las opciones `scripts` y `styles` del objetivo de compilación en el archivo de configuración de compilación del espacio de trabajo [`angular.json`][GuideWorkspaceConfig]. -For example, to use the [Bootstrap 4][GetbootstrapDocs40GettingStartedIntroduction] library +Por ejemplo, para usar la librería [Bootstrap 4][GetbootstrapDocs40GettingStartedIntroduction]: -1. Install the library and the associated dependencies using the npm package manager: +1. Instala la librería y las dependencias asociadas usando el gestor de paquetes npm: @@ -95,7 +95,7 @@ For example, to use the [Bootstrap 4][GetbootstrapDocs40GettingStartedIntroducti -1. In the `angular.json` configuration file, add the associated script files to the `scripts` array: +1. En el archivo de configuración `angular.json`, agrega los archivos de script asociados al array `scripts`: @@ -107,7 +107,7 @@ For example, to use the [Bootstrap 4][GetbootstrapDocs40GettingStartedIntroducti -1. Add the `bootstrap.css` CSS file to the `styles` array: +1. Agrega el archivo CSS `bootstrap.css` al array `styles`: @@ -118,12 +118,12 @@ For example, to use the [Bootstrap 4][GetbootstrapDocs40GettingStartedIntroducti -1. Run or restart the `ng serve` Angular CLI command to see Bootstrap 4 work in your application. +1. Ejecuta o reinicia el comando `ng serve` de Angular CLI para ver Bootstrap 4 funcionar en tu aplicación. -### Using runtime-global libraries inside your app +### Usar librerías globales en tiempo de ejecución dentro de tu aplicación -After you import a library using the "scripts" array, do **not** import it using an import statement in your TypeScript code. -The following code snippet is an example import statement. +Después de importar una librería usando el array "scripts", **no** la importes usando una declaración de importación en tu código TypeScript. +El siguiente fragmento de código es un ejemplo de declaración de importación. @@ -131,17 +131,17 @@ import * as $ from 'jquery'; -If you import it using import statements, you have two different copies of the library: one imported as a global library, and one imported as a module. -This is especially bad for libraries with plugins, like JQuery, because each copy includes different plugins. +Si la importas usando declaraciones de importación, tienes dos copias diferentes de la librería: una importada como librería global, y una importada como módulo. +Esto es especialmente malo para librerías con plugins, como JQuery, porque cada copia incluye diferentes plugins. -Instead, run the `npm install @types/jquery` Angular CLI command to download typings for your library and then follow the library installation steps. -This gives you access to the global variables exposed by that library. +En su lugar, ejecuta el comando `npm install @types/jquery` de Angular CLI para descargar tipados para tu librería y luego sigue los pasos de instalación de la librería. +Esto te da acceso a las variables globales expuestas por esa librería. -### Defining typings for runtime-global libraries +### Definir tipados para librerías globales en tiempo de ejecución -If the global library you need to use does not have global typings, you can declare them manually as `any` in `src/typings.d.ts`. +Si la librería global que necesitas usar no tiene tipados globales, puedes declararlos manualmente como `any` en `src/typings.d.ts`. -For example: +Por ejemplo: @@ -149,7 +149,7 @@ declare var libraryName: any; -Some scripts extend other libraries; for instance with JQuery plugins: +Algunos scripts extienden otras librerías; por ejemplo con plugins de JQuery: @@ -157,8 +157,8 @@ $('.test').myPlugin(); -In this case, the installed `@types/jquery` does not include `myPlugin`, so you need to add an interface in `src/typings.d.ts`. -For example: +En este caso, el `@types/jquery` instalado no incluye `myPlugin`, así que necesitas agregar una interfaz en `src/typings.d.ts`. +Por ejemplo: @@ -168,7 +168,7 @@ interface JQuery { -If you do not add the interface for the script-defined extension, your IDE shows an error: +Si no agregas la interfaz para la extensión definida por el script, tu IDE muestra un error: