Angular 2组件可以外部化吗?

时间:2016-11-02 09:33:15

标签: git angular architecture npm

TL; DR

是否可以在Angular 2应用中为组件提供package.json之类的内容?

长版

我们的应用程序组件正在独立开发。他们有自己的服务,常量和国际化字符串。每次更新或更改组件时,都会更新应用程序版本。有没有办法我们可以只为每个组件编写一个组件并为每个组件分别存储库;每个被声明为主应用程序的依赖?

我的想法

  • 在用于开发组件的每台计算机上创建一个虚拟应用程序
  • 使用组件并将其提交到存储库
  • 主要应用程序的构建过程将这些存储库指定为依赖项,并在构建期间提取它们(特定版本)。
  • 另一项任务将它们复制到应用程序目录(来自node_modules

问题

之前有没有人这样做过?有没有更好的方法呢?

2 个答案:

答案 0 :(得分:2)

我知道如何在本地建立类似的东西。

你可以有这样的目录结构:

angular
|
---- common_files
      |
      ----- package.json
      |
      ----- index.ts
      |
      ----- catalog1
            |
            ---- package.json
            |
            ---- some_file_with_service_model_comopnent.ts
            |
            ---- index.ts    - this is regular barrel file
      |
      ----- catalog2
|
---- app1
     |
     ------ package.json
|
---- apps
     |
     ------ package.json

/角度/ common_files /

{
  "name": "common-modules",
  "version": "0.9.6",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "tsc -w",
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "pack": "webpack"
  },
  "typings": "./index.d.ts",
  "author": "Maciej Sobala",
  "license": "UNLICENSED",
  "dependencies": {
    "@angular/common": "2.0.0",
    "@angular/compiler": "2.0.0",
    "@angular/core": "2.0.0",
    "@angular/forms": "2.0.0",
    "@angular/http": "2.0.0",
    "@angular/material": "2.0.0-alpha.9-3",
    "@angular/router": "3.0.0",
    "ng2-cookies": "^1.0.2",
    "rxjs": "5.0.0-beta.12",
    "typescript": "2.0.0",
    "typescript-collections": "^1.2.3",
    "zone.js": "^0.6.12"
  },
  "private": "true",
  "devDependencies": {
    "@types/body-parser": "0.0.29",
    "@types/compression": "0.0.29",
    "@types/cookie-parser": "^1.3.29",
    "@types/express": "^4.0.32",
    "@types/express-serve-static-core": "^4.0.33",
    "@types/hammerjs": "^2.0.32",
    "@types/mime": "0.0.28",
    "@types/node": "^6.0.38",
    "@types/core-js": "^0.9.34",
    "webpack": "^1.13.2",
    "webpack-merge": "^0.14.0",
    "angular2-template-loader": "^0.4.0",
    "awesome-typescript-loader": "~1.1.1"
  }
}

/angular/common_files/index.ts:

export * from './catalog1/index';
export * from './catalog2/index';

/angular/common_files/catalog1/package.json:

{
  "name": "common-modules/catalog1",
  "main": "index.js"
}

现在,您可以使用common编译npm run tsc。之后,您可以在app1app2

中重复使用它们
npm install ../common/ --save

这将在app1 package.json中创建条目:

"dependencies": {
    "common-modules": "file:///Users/my_name/Documents/work/my_project/angular/common_files",
  }

之后,您可以从app1和/或app2的文件中导入模块     从' common-modules / catalog1';

导入{something}

您还应该查看以下链接:https://docs.npmjs.com/private-modules/intro

答案 1 :(得分:0)

比我想象的要简单。只需将组件文件作为单独的模块从应用程序中移出。 npm install --save它到应用程序并更新app.module.ts文件以指向它。 Angular CLI将自动处理其余部分。

app.module.ts

import { ProfileCardComponent } from '@yoloinc/profile-card-component/profile-card.component';