如何本地化我的 Angular 11 库?

Rod*_*eas 8 angular angular-library angular-localize

我正在将我的 Angular 11 应用程序重构为库。我的常规应用程序是本地化的,@angular/localize用作开发依赖项,因此我$localize在我的部分代码中使用了该指令。我需要将带有此指令的代码移动到库中,但我不知道如何执行此操作。

在我的库package.json文件中,我添加了一个 peer-dependency on@angular/localize以匹配我的应用程序中的 devDependency:

{
  "name": "example",
  "version": "0.0.1",
  "peerDependencies": {
    "@angular/common": "^11.0.0",
    "@angular/core": "^11.0.0",
    "@angular/localize": "~11.0.0"
  },
  "dependencies": {
    "tslib": "^2.0.0"
  }
}
Run Code Online (Sandbox Code Playgroud)

但是,编译器报告说,$localize当我尝试执行ng build <library name>.

× Compiling TypeScript sources through NGC
ERROR: projects/example/src/lib/example.service.ts:52:23 - error TS2304: Cannot find name '$localize'.

52         description = $localize `example localized text`;
                         ~~~~~~~~~
Run Code Online (Sandbox Code Playgroud)

如何$localize在我的库中使用该指令?

>ng version

     _                      _                 ____ _     ___
    / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
   / ? \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
  / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
 /_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
                |___/
    

Angular CLI: 11.0.1
Node: 12.18.3
OS: win32 x64

Angular: 11.0.0
... animations, cdk, common, compiler, compiler-cli, core, forms
... localize, material, platform-browser
... platform-browser-dynamic, router
Ivy Workspace: Yes

Package                         Version
---------------------------------------------------------
@angular-devkit/architect       0.1100.1
@angular-devkit/build-angular   0.1100.1
@angular-devkit/core            11.0.1
@angular-devkit/schematics      11.0.1
@angular/cli                    11.0.1
@schematics/angular             11.0.1
@schematics/update              0.1100.1
ng-packagr                      11.0.3
rxjs                            6.6.3
typescript                      4.0.5
Run Code Online (Sandbox Code Playgroud)

Moh*_*yan 12

第一:安装@angular/localize包。

npm i @angular/localize -D
Run Code Online (Sandbox Code Playgroud)

第二entryFile在你的ng-package.json文件中查找,就我而言public-api.ts

npm i @angular/localize -D
Run Code Online (Sandbox Code Playgroud)

第三:就我而言,添加import '@angular/localize/init';到您的entryFilepublic-api.ts

{
  "$schema": "../../node_modules/ng-packagr/ng-package.schema.json",
  "dest": "../../dist/ngx-my-lib",
  "lib": {
    "entryFile": "src/public-api.ts" // <=== this line
  }
}
Run Code Online (Sandbox Code Playgroud)


小智 2

不确定,尝试将其添加到您的条目文件中:

import '@angular/localize/init';
Run Code Online (Sandbox Code Playgroud)