angular7 - 为 Angular 7 中的特定组件生成单独的构建文件

标签 angular7 angular-components angular-builder

我将使用 Angular 7 Framework 开发一个非常大的应用程序。

我已经使用

创建了一个空白的角度工作区
 ng new angular-app --create-application=false

在这个工作区中,我使用以下命令创建了两个角度应用程序:

 ng generate application app-one

 ng generate application app-two

在这两个应用程序中的每一个中,我都将拥有多个组件,每个组件彼此独立工作。

我正在寻找一种方法来为每个组件创建一个单独的 javascript 构建文件,以减少构建大小。

并使用每个单独构建的 js 文件将每个组件用作 Web 组件。

请阅读我已经尝试过的内容以获得更好的想法。

我尝试了以下步骤:

  1. 为自定义角度元素创建一个带有前缀 custom 的存储库:

    ng new app-name --prefix custom

  2. 添加角度元素包:

    添加@angular/elements

  3. 根据需要创建封装为 native/emulated/none 的自定义元素组件:

    ng g component my-component --inline-style --inline-template -v Native

  4. 在 app.modulte.ts 中定义自定义元素

    import  { Injector} from '@angular/core';
       import  { createCustomElement } from '@angular/elements';
        ...
        export class AppModule {
            constructor(private injector : Injector){
            const el = createCustomElement(MyComponent, {injector : this.injector});
            customElements.define('my-component',el);
    }
            ngDoBootstrap(){ }
        }
  1. 安装 ngx-build-plus 包以构建单个包(例如 Angular Elements):

    npm i ngx-build-plus

  2. 更新 angular.json 文件中应用程序的构建器部分,使其指向 ngx-build-plus:

    " builder ": "ngx-build-plus:build",

  3. 在 package.json 中添加脚本以运行构建器:

    "build:ngx": "ng build --prod --output-hashing none --single-bundle true"

  4. 如果需要,通过创建一个 js 文件“concat_ngx.js”将 scripts.js 和 main.js 合并到创建的 dist 文件夹中:

     const fs = require('fs-extra');
        const concat = require('concat');
        (async function build() {
            const files = [
                './dist/<your_project>/scripts.js',
                './dist/<your_project>/main.js',
            ]
            await fs.ensureDir('elements_ngx')
            await concat(files, 'elements_ngx/combined-script.js');
        })()   
  1. 运行文件得到单个js文件:

    节点concat_ngx.js

  2. 在任何 Angular/其他项目中使用 js 文件来使用创建的自定义组件。

但这里的问题是我每次都必须在 app-module.ts 中更改组件 Bootstrap

我需要一种自动化的方式来在运行时更改 app-module.ts 中的引导。

但这里的问题是我每次都必须在 app-module.ts 中更改组件 Bootstrap

我需要一种自动化的方式来在运行时更改 app-module.ts 中的引导。

最佳答案

在 Angular 7 中,添加默认或自动引导:-

这是 Angular 应用程序 Bootstrap 和 main.ts 保存应用程序起点的默认方式。

platformBrowserDynamic().bootstrapModule(AppModule);

有关更多信息,请参见此处:- https://medium.com/learnwithrahul/ways-of-bootstrapping-angular-applications-d379f594f604

关于angular7 - 为 Angular 7 中的特定组件生成单独的构建文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55783925/

相关文章:

angular - 如何在 Angular 7 中增加超过 2 分钟的 HTTP 请求超时?

Angular7输入类型文件上传不起作用

angular - 如何从 Angular 7 中的 Observable 返回对象

Angular7 放置区 : click event not triggered

angular - 在 Angular 单个组件中导入第 3 方 javascript 库

javascript - 查看未注入(inject)或警告 : Tried to load angular more than once

Angular Ivy 编译器和 webpack