使用外部代码的最佳实践是什么,例如在 Node 模块中找到的代码,角度?
我想用这个 https://www.npmjs.com/package/positionsizingcalculator我的角度应用程序中的 Node 模块。我创建了一个旨在包装 Node 模块的角度服务,现在我想让该服务使用 Node 模块。
'use strict';
angular.module('angularcalculator')
.service('MyService', function () {
this.calculate = function () {
return {
//I want to call the node module here, whats the best practice?
};
}
});
最佳答案
为此,我会打开包装并从中取出 .js。这个包是 MIT 许可证,所以我们可以做任何我们想做的事。如果您导航到 /node_modules/positionsizingcalculator/
,您会找到一个 index.js
。打开它,您会看到模块导出,它接受一个返回对象的函数。
您会注意到这是一个与 .factory
极其相似的模式,它也采用一个返回对象(或构造函数,取决于您的模式)的函数。所以我会做以下事情
.factory('positionsizingcalculator', function(){
basicValidate = function (argument) {
... //Insert whole declaration in here
return position;
})
然后将它注入(inject)到你需要的地方:
.controller('AppController', function(positionsizingcalculator){
//use it here as you would in node after you inject it via require.
})
-- 编辑:这对于一次性获取 JS 很有用,但如果您想要一个更具扩展性的解决方案,http://browserify.org/是一个更好的选择。它允许您将您的需求转换为一个包。请注意,如果您为整个站点制作一个 require bundle,这可能会导致删除更多您可能需要的代码,因为这不是真正的 AMD,并且您需要加载客户端可能需要的所有内容,除非您制作特定于页面的 bundle 。
您仍然希望在 factory
中执行 require 并将其返回,以将其保留在 angular 的依赖注入(inject)框架中。
关于node.js - 在angularjs中使用 Node 模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29710239/