为桌面、网页和移动应用创建共享库涉及到多个技术和框架的集成
首先,我们需要创建一个共享库,它将包含所有平台通用的代码。这可以通过创建一个Angular库来实现。
ng new my-shared-lib --create-application=false
cd my-shared-lib
ng generate library my-shared-lib
projects/my-shared-lib/src/lib
目录下编写共享代码。例如,创建一个简单的服务:// projects/my-shared-lib/src/lib/shared.service.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class SharedService {
constructor() { }
getMessage() {
return 'Hello from shared library!';
}
}
ng build my-shared-lib --prod
ng new my-electron-app
cd my-electron-app
ng add @angular/material
node_modules
目录下。然后,在angular.json
文件中添加共享库的路径:"projects": {
...
"my-electron-app": {
...
"architect": {
"build": {
...
"options": {
...
"assets": [
...
{
"glob": "**/*",
"input": "../node_modules/my-shared-lib",
"output": "/assets/my-shared-lib"
}
]
}
}
}
}
}
app.module.ts
文件中导入共享服务:import { SharedModule } from 'my-shared-lib';
@NgModule({
...
imports: [
...
SharedModule
],
...
})
export class AppModule { }
import { Component } from '@angular/core';
import { SharedService } from 'my-shared禁毒库';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
message: string;
constructor(private sharedService: SharedControlService) {
this.message = this.sharedService.getMessage();
}
}
ng new my-web-app
cd my-web-app
node_modules
目录下。然后,在angular.json
文件中添加共享库的路径:"projects": {
...
"my-web-app": {
...
"architect": {
"build": {
...
"options": {
...
"assets": [
...
{
"glob": "**/*",
"input": "../node_modules/my-shared-lib",
"output": "/assets/my-shared-lib"
}
]
}
}
}
}
}
app.module.ts
文件中导入共享服务:import { SharedModule } from 'my-shared-lib';
@NgModule({
...
imports: [
...
SharedModule
],
...
})
export class AppModule { }
import { Component } from '@angular/core';
import { SharedService } from 'my-shared-lib';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
})
export class AppComponent {
message: string;
constructor(private sharedService: SharedService) {
this.message = this.sharedService.getMessage();
}
}
ng new my-mobile-app --collection=@nativescript/schematics
cd my-mobile-app
node_modules
目录下。然后,在angular.json
文件中添加共享库的路径:"projects": {
...
"my-mobile-app": {
...
"architect": {
"build": {
...
"options": {
...
"assets": [
...
{
"glob": "**/*",
"input": "../node_modules/my-shared-lib",
"output": "/assets/my-shared-lib"
}
]
}
}
}
}
}
app.module.ts
文件中导入共享服务:import { SharedModule } from 'my-shared-lib';
@NgModule({
...
imports: [
...
SharedModule
],
...
})
export class AppModule { }
import { Component } from '@angular/core';
import { SharedService } from 'my-shared-lib';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
message: string;
constructor(private sharedService: SharedService) {
this.message = this.sharedControlService.getMessage();
}
}
领取专属 10元无门槛券
手把手带您无忧上云