我有一些 angularjs 文件,它可以通过 RESTAPI 访问第三方服务。 比如说,我有多个 java 应用程序需要使用相同的 angularjs 文件。 共享文件的最佳方式是什么。
基本上,在过去(我指的是后端代码),我们会编写一个作为服务部署的应用程序,并且所有其他应用程序都使用该服务。我如何用 Angular 实现这一点..请记住,我主要是一名后端开发人员并进入了新的前端世界
谢谢
最佳答案
我建议使用Bower用于维护可重复使用的组件。在自己的模块中开发独立功能,无论它们是指令、服务还是任何 Angular 组件,然后将它们作为 Bower 依赖项安装到任何您单独的 Angular 应用程序。
鲍尔有documentation on creating packages ,布莱恩·福特 (Brian Ford) 写了一篇 nice (albeit a bit outdated at places) tutorial关于使用 Bower 编写可重用的 Angular 组件。
所以,基本上你的工作流程会是这样的:
开始开发您的模块。如果它是已经存在的东西,你可以将它从当前位置拉出来。
mkdir your-component-name cd your-component-name $editor your-module.js
一旦您启动了
your-module.js
(无需先完成开发,如果您正在开发一个全新的组件,实际上最好不要完成),就到了初始化您的 Bower组件。bower init
系统会要求您提供一些初始设置,例如组件名称(默认为目录名称,例如
your-component-name
)、初始版本号、主文件(很可能是your-module.js
) 等。对于大多数情况,默认值就可以了。成功运行bower init
后,您将得到bower.json
,它可能看起来像这样:{ "name": "your-component-name", "version": "0.0.0", "main": 'your-module.js', "license": "MIT", "ignore": [ "**/.*", "node_modules", "bower_components", "test", "tests" ] }
当然,您可以手动完成所有这些操作,但最好使用
bower init
辅助工具。继续开发。如果您有任何外部依赖项,您也可以使用 Bower 添加它们:
bower install external-dependency --save
开发完成了吗?现在是发布您的组件以便可以在您的应用程序中使用它的时候了。如果您尚未初始化 Git存储库,从它开始:
git init .
添加您的作品,提交并标记它:
git add <your-component-contents> git commit -m "v0.0.0" git tag v0.0.0
这是除了
bower.json
中version
属性的值之外的部分(注意:Brian Ford's tutorial正在说话关于component.json
- 不幸的是,这是过时的东西),您将能够在所有应用程序中轻松维护您的组件。需要改变吗?只需执行此操作,增加版本号、提交、标记并在需要时运行bower update
。下一步是将代码发布到 Git 存储库中,例如 GitHub
git remote add origin <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fa9d938eba9d938e928f98d4999597" rel="noreferrer noopener nofollow">[email protected]</a>:your-github-user-name/angular-your-component-name.git git push -u origin master
然后就可以安装组件了:
bower install your-github-user-name/angular-your-component-name
该组件甚至可以从私有(private)存储库安装,例如,如果您不想在公司外部发布该组件(请参阅 Brian Ford's tutorial 中的标题“Bower Package Stewardship”了解更多信息详细信息):
bower install <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6f08061b2f08061b071a0d410c0002" rel="noreferrer noopener nofollow">[email protected]</a>:your-github-user-name/angular-your-component-name.git # or from any other arbitrary git repo
另一方面,如果您确实希望发布新创建的组件,则应该考虑注册它:
bower register angular-your-component-name <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4e29273a0e29273a263b2c602d2123" rel="noreferrer noopener nofollow">[email protected]</a>:your-github-user-name/angular-your-component-name.git
这样就可以搜索到它,并且安装起来会更容易:
bower install angular-your-component-name
开始在 Angular 应用程序中使用您的组件。每当您发现某个应用程序存在错误/缺少功能时,您都可以修复您的组件,发布新版本,然后逐一更新您的应用程序。
然后还有npm您可以使用它来代替 Bower 。工作流程也几乎相同,当然与工具特定部分不同,但其他方面没有太大差异。我不会进入npm不过,现在包装细节只是想将其作为替代工具提及。
关于angularjs - 在多个应用程序之间重用 AngularJS 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30329897/