Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/compatible anglur12 #368

Merged
merged 7 commits into from
Sep 10, 2021
Merged

Feat/compatible anglur12 #368

merged 7 commits into from
Sep 10, 2021

Conversation

maoxiaoke
Copy link
Collaborator

@maoxiaoke maoxiaoke commented Aug 22, 2021

@maoxiaoke
Copy link
Collaborator Author

Angualr 接入 icestark

以 Angular 12 应用为例,介绍 Angular 接入 icestark 的步骤:

  1. 入口文件新增生命周期函数

main.ts 是 Angular 应用的入口文件,我们在这里增加 icestark 渲染所需的生命周期函数。

// src/main.ts

import { NgModuleRef } from '@angular/core';
import isInIcestark from '@ice/stark-app/lib/isInIcestark';
import setLibraryName from '@ice/stark-app/lib/setLibraryName';

// 注意:`setLibraryName` 的入参需要与 webpack 工程配置的 output.library 保持一致
setLibraryName('angular-micro-name');

let app: void | NgModuleRef<AppModule>;

if (!isInIcestark()) {
  platformBrowserDynamic().bootstrapModule(AppModule)
    .catch(err => console.error(err));
}

// 导出生命周期函数
export async function mount () {
  app = await platformBrowserDynamic().bootstrapModule(AppModule)
    .catch(err => console.error(err));
}

export function unmount () {
  // @ts-ignore
  app.destroy();
}
  1. 定义基准路由

因为 Angular 在主应用渲染时的基准路由与微应用单独渲染时的基准路由可能不一致。因此,修改 src/app/app-routing.module.ts

// src/app/app-routing.module.ts

import { APP_BASE_HREF } from '@angular/common';
import getBasename from '@ice/stark-app/lib/getBasename';
import isInIcestark from '@ice/stark-app/lib/isInIcestark';

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
  // Added by icestark 修改 anglur 应用的 basename
  providers: [{ provide: APP_BASE_HREF, useValue: isInIcestark() ? getBasename() : '/' }]
})
export class AppRoutingModule { }
  1. 自定义 webpack 配置,将资源打包成 umd 资源

开启 Angular 自定义 webpack 能力,需要安装 @angular-builders/custom-webpack

npm i -D @angular-builders/custom-webpack@12

注意:@angular-builders/custom-webpack 版本强相关,注意安装想对应的版本

接下来,修改配置文件 angular.json ,找到 build 和 serve 配置,修改成下面的代码:

// angular.json

"build": {
-  "builder": "@angular-devkit/build-angular:browser",
+  "builder": "@angular-builders/custom-webpack:browser",
  	"options": {
+				"customWebpackConfig": {
+           "path": "custom-webpck.config.js"
+       },
			"outputPath": "dist/my-first-project",
			...
	}
},
"serve": {
-		 "builder": "@angular-devkit/build-angular:dev-server",
-    "configurations": {
-      "production": {
-        "browserTarget": "my-first-project:build:production"
-      },
-      "development": {
-        "browserTarget": "my-first-project:build:development"
-      }
-    },
-    "defaultConfiguration": "development"
+    "builder": "@angular-builders/custom-webpack:dev-server",
+     "options": {
+       "browserTarget": "my-first-project:build"
+     }
}

并定义 custom-webpack.config.js 文件

// custom-webpack.config.js
module.exports = {
  devServer: {
    headers: {
      'Access-Control-Allow-Origin': '*',
    },
  },
  output: {
    library: `angular-micro-name`,
    libraryTarget: 'umd',
  },
  optimization: {
    splitChunks: false,
    runtimeChunk: false,
  }
}
  1. 为防止 Angualr 与其他 Angular 应用冲突,建议给 <app-root> 加上一个唯一的 id,比如当前应用的名称:
// src/index.html

- <app-root></app-root>
+ <app-root id="angular-app"></app-root>

src/app/app.component.ts 修改 Angular 挂载的节点:

// src/app/app.component.ts

@Component({
  // Added by icestark: 表示唯一的 angluar,防止命名冲突
- selector: 'app-root',
+ selector: '#angular-app app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'my-first-project';
}
  1. 如何增加 publicPath

由于 Angular 默认生成的 html 如下:

// dist

<!DOCTYPE html><html lang="en"><head>
  <meta charset="utf-8">
  <title>MyFirstProject</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
<link rel="stylesheet" href="http://localhost:4200/styles.31d6cfe0d16ae931b73c.css"></head>
<body>
  <app-root></app-root>
<script src="polyfills.e5b270c380957aa42f5e.js" defer></script><script src="main.47063159316ce8e7599f.js" defer></script>

</body></html>

在本地调试时,需要修改 js 资源和 css 资源的 publicPath 来保证设置正确的资源路径。比如应用启动在 localhost:4200/ 则应用启动时,可以配置:

npm run start -- --deploy-url http://localhost:4200/

@maoxiaoke maoxiaoke changed the base branch from master to release/2.6.0 August 23, 2021 12:28
src/util/handleAssets.ts Outdated Show resolved Hide resolved
@maoxiaoke maoxiaoke requested a review from ClarkXia September 9, 2021 03:51
src/util/handleAssets.ts Outdated Show resolved Hide resolved
const baseElementMatch = html.match(BASE_LOOSE_REGEX);

const baseElements = domContent.getElementsByTagName('base');
const hasBaseElement = baseElements.length;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

baseElements.length > 0

// add base URI for absolute resource.
// see more https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base
const base = document.createElement('base');
base.href = entry;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

说明下 base 设置即便是 /xx/index.html 加载也可以

}

const { html } = cachedContent;
const { html, assets } = processHtml(cachedContent ?? htmlContent, entry || href);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

执行结果上目前是没问题的,看下 cachedContent 设置为 false/ '' 的情况下 是拿 htmlContent 作为兜底还是以设置的值为准

@maoxiaoke maoxiaoke merged commit 64efbce into release/2.6.0 Sep 10, 2021
@delete-merged-branch delete-merged-branch bot deleted the feat/compatible-anglur12 branch September 10, 2021 06:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants