在多个项目中共享一个角度库

Vik*_*iya 10 angular angular6 angular-builder angular7

我正在做一个由后端+前端组成的7+项目。现在,我面临一个需求,我需要再创建一个包含前端+后端的项目。但是存在一些可重用的前端代码,可以在两个应用程序之间重用。

我的个人结构

这里

需求

这里

因此,当我阅读有关图书馆的概念时,我会发现

1)创建两个前端应用程序并共享一个公共库

因为我使用通过Visual Studio创建的(如图所示asp.net角模板项目,我不能采取这种方法在这里)。两个应用程序(项目一和项目二)具有自己的FE + BE。因此,我无法将两个FE应用程序分组到同一文件夹中,并使它们使用共享库。

2)创建库并上传到npm并用作依赖项

我不能采用这种方法,因为代码是专有的,不能在网络外部共享。此外,没有本地公司npm注册表可使用公司npm。

我知道可以使用库概念来完成。但是我不了解如何在多个应用程序中完成此操作。有人可以提供解决方案吗?谢谢 !

kat*_*des 5

1)。您可以尝试为您的库使用 npm pack:

"scripts": {
   ...
   "build_lib": "ng build --prod example-lib",
   "npm_pack": "cd dist/example-lib && npm pack",
   "package": "npm run build_lib && npm run npm_pack"
}
Run Code Online (Sandbox Code Playgroud)

2)运行“npm pack”后,生成的文件将类似于:example-lib-0.0.1.tgz

3)您可以使用以下命令从其他项目安装: npm install ../{some-paths}/example-lib/dist/example-lib/example-lib-0.0.1.tgz

在此处查看更多详细信息:https://blog.angularindepth.com/creating-a-library-in-angular-6-part-2-6e2bc1e14121


小智 5

考虑到您在 OP 中提到的目录方案,您可以通过本地路径添加您的库,如 NPM 文档中所述:本地路径

- Root
|
 -- Project One 
|
 -- Project Two
|
 -- Library usued across both projects
Run Code Online (Sandbox Code Playgroud)

例如在package.json一号工程,您可以添加库的依赖关系:

"dependencies" : {
  "my-shared-library" : "file:../Library usued across both projects",
}
Run Code Online (Sandbox Code Playgroud)

PS我不确定库文件夹名称中是否允许空格,但您可以尝试找出它。但我假设你无论如何都不会使用空格。


替代解决方案和进一步计划

2)创建库并上传到 npm 并用作依赖项我不能采用这种方法,因为代码是专有的,不能在网络外共享。也没有本地企业 npm 注册表来使用企业 npm。

这并不准确。您确实可以将此方法作为替代解决方案,或者如果您认为将来可以在另一个项目中使用此库。有一种方法可以做到这一点,如 NPM 文档中所述:Git URLs as Dependencies

包.json

"dependencies" : {
  "my-shared-library" : "Git repo address here. There are various ways to specify an address. See below.",
}
Run Code Online (Sandbox Code Playgroud)

如何将库添加为依赖项

  • 假设您为此库创建了一个新存储库:
"dependencies" : {
  "my-shared-library" : "git+ssh://git@my-companys-treasure.com/my-shared-library.git",
}
Run Code Online (Sandbox Code Playgroud)

这样您甚至可以使用不同版本的库。假设你开发一个新版本(即4.2.0你的库中)Project One和没有准备好或者不应该被使用Project Two,在package.jsonProject One,你可以像这样添加它:

"dependencies" : {
  "my-shared-library" : "git+ssh://git@my-companys-treasure.com/my-shared-library.git#branch-v4.2.0",
}
Run Code Online (Sandbox Code Playgroud)
  • 或者,您可以branch-for-my-shared-library在当前存储库中创建一个新分支,例如(假设项目一项目二都推送到同一个存储库):
"dependencies" : {
  "my-shared-library" : "git+ssh://git@my-companys-treasure.com/my-current-project.git#branch-for-my-shared-library",
}
Run Code Online (Sandbox Code Playgroud)

另请注意,您可以在 URL 中指定多种协议,如文档中所述:

协议是 git、git+ssh、git+http、git+https 或 git+file 之一。

补充说明:

快乐编码。


Cri*_*ìna 3

您可以使用npm 链接

包文件夹中的 npm 链接将在全局文件夹 {prefix}/lib/node_modules/ 中创建一个符号链接,该符号链接链接到执行 npm link 命令的包。

很快,如果您进入库文件夹并输入:

npm link
Run Code Online (Sandbox Code Playgroud)

然后您可以移入要使用该库的项目并输入:

npm link <project-name>
Run Code Online (Sandbox Code Playgroud)

<project-name>文件中存在的名称在哪里package.json

这就足够了。如果您想在网络中共享库而不复制和粘贴源代码,那么,也许最好要求您的公司支付私人存储库的费用:)