javascript 如何在 angular 中使用 npm 模块?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34329517/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 17:34:27  来源:igfitidea点击:

How to use npm module in angular?

javascriptangularjsnode.jsbraintree

提问by c0de

I am trying to use braintree-webnpm module with AngularJS since I get errors when I try and include it in the template with:

我正在尝试将Braintree-webnpm 模块与 AngularJS一起使用,因为当我尝试将它包含在模板中时出现错误:

<script src="https://js.braintreegateway.com/v2/braintree.js"></script>

I have a state called billing that I use to route to my template with the controller, 'BillingController'. I want to be able to inject braintree-web and myscript.js:

我有一个称为 billing 的状态,我用它来路由到带有控制器“BillingController”的模板。我希望能够注入 Braintree-web 和 myscript.js:

<script>
  braintree.setup(
          // Replace this with a client token from your server
          clientToken,
          "dropin", {
            container: "payment-form",
            form: "checkout",
          });
</script>

Please help. how can I do this?

请帮忙。我怎样才能做到这一点?

EDIT:

编辑

Currently, this is placed a the bottom of my

目前,这是放在我的底部

<!-- braintree sdk -->
    <script src="https://js.braintreegateway.com/v2/braintree.js"></script>

    <!-- braintree setup -->
    <script>
      var clientToken = removed;
      braintree.setup(
          // Replace this with a client token from your server
          clientToken,
          "dropin", {
            container: "payment-form",
            form: "checkout",
          });
    </script>

These are the errors I'm getting:

这些是我得到的错误:

enter image description here

在此处输入图片说明

Looks to me like the braintree script is not loading(?)

在我看来,braintree 脚本没有加载(?)

Thanks for the help

谢谢您的帮助

回答by ssuperczynski

Do you use braintree-webfrom this url? https://github.com/jeffcarp/braintree-angular

braintree-web从这个网址使用吗?https://github.com/jeffcarp/braintree-angular

This is module special for angular. Then you should create file like app.jsand paste this code:

这是 angular 的专用模块。然后你应该创建类似的文件app.js并粘贴以下代码:

var yourApp = angular
  .module('yourApp', ['braintree-angular'])
  .constant('clientTokenPath', '/path-or-url-to-your-client-token');

For example:

例如:

(function () {
    'use strict';

    var app = angular.module('yourModuleName', [
        'braintree-angular'
    ]);

    app.constant('clientTokenPath', '/path-or-url-to-your-client-token');

    app.config(['$interpolateProvider', function ($interpolateProvider) {
        $interpolateProvider.startSymbol('[[');
        $interpolateProvider.endSymbol(']]');
    }]);


}());

Your controller.js could be like this:

你的 controller.js 可能是这样的:

(function() {
    'use strict';

    angular
            .module('yourModuleName')
            .controller('DashboardCtrl', DashboardCtrl);

    DashboardCtrl.$inject = ['$scope', '$braintree'];

    function DashboardCtrl($scope, $braintree) {

        var client;
        $scope.creditCard = {
            number: '',
            expirationDate: ''
        };

        var startup = function() {
            $braintree.getClientToken().success(function(token) {
                client = new $braintree.api.Client({
                    clientToken: token
                });
            });
        };

        $scope.payButtonClicked = function() {

            // - Validate $scope.creditCard
            // - Make sure client is ready to use

            client.tokenizeCard({
                number: $scope.creditCard.number,
                expirationDate: $scope.creditCard.expirationDate
            }, function (err, nonce) {

                // - Send nonce to your server (e.g. to make a transaction)

            });
        };

        startup();

    }


}());

Notice that app.jsshould be included before rest of your controllers, factories and services, and after you angular.js and braintree.js library.

请注意,它app.js应该包含在您的控制器、工厂和服务的其余部分之前,以及 angular.js 和 Braintree.js 库之后。

回答by danday74

I think your best hope is browserify. I have never tried it myself but I think the idea behind it is converting NodeJS code into a format the browser can understand.

我认为你最大的希望是 browserify。我自己从未尝试过,但我认为它背后的想法是将 NodeJS 代码转换为浏览器可以理解的格式。

npm i braintree
npm i browserify

Maybe try a small test and see if it works?

也许尝试一个小测试,看看它是否有效?

回答by ste2425

To expand on @danday74 we use browserify like this at work.

为了扩展@danday74,我们在工作中使用这样的 browserify。

In a nutshell this is how we use it.

简而言之,这就是我们使用它的方式。

So Browserifyif your not aware its a nodejs CLI that lets you use NodeJs style requirefor client code. It allows you to write well structured, modular client code and build it into a single file to include into your page. Another benefit is every file is scoped to that single file. So no more accidental global's (if your not using strict mode). The only things exposed from your files are things that you explicitly export.

所以Browserify如果你不知道它是一个 nodejs CLI,它允许你require对客户端代码使用 NodeJs 样式。它允许您编写结构良好的模块化客户端代码,并将其构建到单个文件中以包含在您的页面中。另一个好处是每个文件都限于该单个文件。所以没有更多的意外全局(如果你不使用严格模式)。从您的文件中公开的唯一内容是您明确导出的内容。

Because its a CLI you to have to install it globally so you can use it on the command line.

因为它是一个 CLI,所以您必须全局安装它,以便您可以在命令行上使用它。

npm install -g browserify

Then to run it simply from the command line do

然后简单地从命令行运行它

browserify main.js > output.js

and include that on your page

并将其包含在您的页面上

<script src="output.js"></script>

We personally alias that in our package.jsonas we do other things like linting and sass. here's an example

package.json我们做其他事情(如 linting 和 sass)时,我们个人将其别名为我们的。这是一个例子

{
  "name": "some app",
  "scripts": {
    "build:js": "browserify src/index.js > dist/built.js",
    "build:css": "node-sass sass/main.scss dist/built.css",
    "build": "npm run build:js && npm run build:css"
  }
}

Now we just run npm run buildand it will build out sass and js.

现在我们只需运行npm run build,它将构建 sass 和 js。

What browserify will do is recursively traverse your file looking for requirecalls, it will then travel into that file and repeat. As part of its search path it will look in your node_modulesfolder. This is why you can include modules installed through npm.

browserify 会做的是递归遍历您的文件以查找require调用,然后它将遍历该文件并重复。作为其搜索路径的一部分,它将在您的node_modules文件夹中查找。这就是为什么您可以包含通过npm.

Here's a small example

这是一个小例子

//In a file called data.js located in same folder as main.js
module.exports = [1, 2, 2, 3, 4, 5, 5, 6];


//in a file called main.js
var unique = require('uniq'),
    data = require('./data');

console.log(unique(data)); //[1, 2, 3, 4, 5, 6]

What this will do is first look for a module called uniqinstalled through NPM (as there is no relative or absolute path). It will then look for our own file called data.jslocated in the same folder.

这将首先查找uniq通过 NPM 安装的模块(因为没有相对或绝对路径)。然后它将查找data.js位于同一文件夹中的我们自己的文件。

When would build this with browserify main.js > out.js

什么时候用 browserify main.js > out.js

I hope this helps explain what browserify is and how it can be helpful to manage you structure when you wish to include NPMmodules in the client. I'm aware this won't be suitable for all especially if you have a large application that doesn't use browserify but now i use a build tool like this to write modular code i would never go bacl.

我希望这有助于解释什么是 browserify 以及当您希望NPM在客户端中包含模块时如何帮助管理您的结构。我知道这并不适合所有人,特别是如果您有一个不使用 browserify 的大型应用程序,但现在我使用这样的构建工具来编写模块化代码,我永远不会回头。

回答by shiv

In console do: npm install braintree --save

在控制台中执行: npm install Braintree --save

then in your javascript require('braintree'), now you will have the braintree functions available

然后在您的 javascript require('braintree') 中,现在您将拥有可用的 Braintree 功能