如何在使用angular-cli构建的angular2项目中引入Underscore.js

10

我想在使用angular-cli构建的angular2项目中包含underscore.js,但是我一直未能成功。我尝试了以下方法:

1- 运行命令 npm install underscore --save

2- 运行命令 tsd install underscore

3- 在 index.html 中加入

4- 在 system-config.js 中进行配置

/** Map relative paths to URLs. */
var map = {
    'underscore': '../node_modules/underscore/underscore.js'
};
/** User packages configuration. */
var packages = {
    'underscore': '../node_modules/underscore/underscore.js'
};

5- 导入 * as _ from 'underscore';

但是在运行时,underscore.js 没有被复制到“dist”目录中,浏览器会抱怨找不到 underscore.js。我认为在第4点上我可能遗漏了什么。 非常感谢任何帮助,因为我正在开始学习 angular2。 请记住,该项目是由 angular-cli 创建的,而不是其他种子项目。除了 Underscore.js 之外,项目运行良好。

[编辑] package.json 中的依赖关系为 "underscore": "^1.8.3"

7个回答

8

使用 Angular CLI 1.0.0-rc.1,推荐的解决方案在这里描述:

Angular2 2.4 如何将外部库(如 Underscore)加载到 angular2 中。

npm install underscore --save // save to dependencies: required to run
npm install @types/underscore --save-dev // save to dev dependencies: required in dev mode

那么在你的组件类中:

import * as _ from 'underscore';
...
subtitle = _.head(['xyz'])

另外,还有一种加载“静态”脚本的方法可以在angular-cli中实现,如此处所述https://www.npmjs.com/package/angular-cli#global-library-installation:

在.angular-cli.json中将其添加到脚本数组中:

"scripts": ["../node_modules/underscore/underscore.js"]

这将加载underscore.js,但这不是在您的TypeScript类中使用它的好方法。

4

使用npm安装underscore库 前往yourappname/src/typings.d.ts并添加以下行 declare module 'underscore'; 然后运行ng build。


2

Angular 2完整的三个文件代码片段

package.json

    {
  "name": "angular2-quickstart",
  "version": "1.0.0",
  "scripts": {
    "start": "tsc && concurrently \"npm run tsc:w\" \"npm run lite\" ",
    "lite": "lite-server",
    "postinstall": "typings install",
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "typings": "typings"
  },
  "license": "ISC",
  "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/platform-browser": "2.0.0",
    "@angular/platform-browser-dynamic": "2.0.0",
    "@angular/router": "3.0.0",
    "@angular/upgrade": "2.0.0",
    "angular2-in-memory-web-api": "0.0.20",
    "bootstrap": "^3.3.6",
    "core-js": "^2.4.1",
    "reflect-metadata": "^0.1.3",
    "rxjs": "5.0.0-beta.12",
    "systemjs": "0.19.27",
    "tsd": "^0.6.5",
    "underscore": "^1.8.3",
    "zone.js": "^0.6.23"
  },
  "devDependencies": {
    "concurrently": "^2.2.0",
    "lite-server": "^2.2.2",
    "typescript": "^2.0.2",
    "typings": "^1.3.2"
  }
}

systemjs.config.js

/**
 * System configuration for Angular 2 samples
 * Adjust as necessary for your application needs.
 */
(function (global) {
  System.config({
    paths: {
      // paths serve as alias
      'npm:': 'node_modules/'
    },
    // map tells the System loader where to look for things
    map: {
      // our app is within the app folder
      app: 'app',
      // angular bundles
      '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
      '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
      '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
      '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
      '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
      '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
      '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
      '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
      // other libraries
      'rxjs':                       'npm:rxjs',
      'underscore':                 'npm:underscore',

      'angular2-in-memory-web-api': 'npm:angular2-in-memory-web-api',
    },
    // packages tells the System loader how to load when no filename and/or no extension
    packages: {
      app: {
        main: './main.js',
        defaultExtension: 'js'
      },


      rxjs: {
        defaultExtension: 'js'
      },
      'underscore':{
       main: './underscore.js', 
       defaultExtension: 'js'
       },
      'angular2-in-memory-web-api': {
        main: './index.js',
        defaultExtension: 'js'
      }
    }
  });
})(this);

tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false
  }
}

typings.json

{
  "globalDependencies": {
    "core-js": "registry:dt/core-js#0.0.0+20160725163759",
    "jasmine": "registry:dt/jasmine#2.2.0+20160621224255",
    "node": "registry:dt/node#6.0.0+20160909174046"
  },
  "ambientDependencies": {
    "underscore": "github:DefinitelyTyped/DefinitelyTyped/underscore/underscore.d.ts#f0990e288ac73d593e982995947567aa2643b828"
  }
}

1- 使用npm安装underscore, 命令:npm install underscore --save 2- 如果没有安装tsd,请先安装tsd,然后使用命令:tsd install underscore 3) 现在执行npm install 4) 最后执行npm start


1

安装 underscore:

npm i underscore --save

在 angular-cli.json 文件中:
"scripts": [
        "../node_modules/underscore/underscore-min.js",
         ...
      ],

执行命令后:

ng build

在组件中:
declare var _: any;
@Component({...})

0
你的项目中有一个叫做 Package.json 的文件吗?如果有,你可以尝试添加这行代码。
"underscore": "^1.8.3",

在这个文件的依赖项中。

system-config.ts 中的修改。

var map = {

    "underscore": "node_modules/underscore",

  };

var packages = {
    'underscore':            { main: 'index.js', defaultExtension: 'js' }
  };

  var packageNames = [
    '@angular/common',
    '@angular/compiler',
    '@angular/core',
    '@angular/http',
    '@angular/platform-browser',
    '@angular/platform-browser-dynamic',
    '@angular/router-deprecated',
    '@angular/testing',
    '@angular/upgrade',
  ];

packageNames.forEach(function(pkgName) {
    packages[pkgName] = { main: 'index.js', defaultExtension: 'js' };
  });

var config = {
    map: map,
    packages: packages,
    paths: {
      "underscore": "/node_modules/underscore.js"
    }
  };

然后执行npm install命令。


是的,package.json有这个,但它没有更新system-config.ts。 - raju
如果您需要更新 system-config.ts,则必须手动执行此操作,就像您处理 package.json 一样。并且在所有这些修改之后运行 npm install。 - Naella
我尝试了您的步骤,但在运行"ng serve"时,出现错误'无法找到模块Underscore'。您能否请提供一个可行的plnkr。先行致谢。 - raju

0
我觉得你可能漏掉了一步?你记得在“angular-cli-build.js”文件中设置下划线吗?这一步告诉clingon将下划线放在供应商文件夹(/dist/vendor)中。
以下是我让下划线工作的方法。
  1. 安装underscore和typings:

    npm install underscore --save
    typings install underscore --save --ambient
    
  2. 在"angular-cli-build.js"中设置underscore:

    module.exports = function(defaults) {
      return new Angular2App(defaults, {
        vendorNpmFiles: [
          'systemjs/dist/system-polyfills.js',
          'systemjs/dist/system.src.js',
          'zone.js/dist/**/*.+(js|js.map)',
          'es6-shim/es6-shim.js',
          'reflect-metadata/**/*.+(js|js.map)',
          'rxjs/**/*.+(js|js.map)',
          '@angular/**/*.+(js|js.map)',
          'moment/moment.js',
          'underscore/underscore.js'
        ]
      });
    };
    
  3. 然后underscore会被编译到vendor文件夹(/dist/vendor)下,现在可以从system.config.ts文件中指向该位置了:

    const map: any = {
      "underscore": "vendor/underscore/underscore.js",
      "moment": "vendor/moment/moments.js"
    };
    
    /** User packages configuration. */
    const packages: any = {
      'underscore': {
        format: 'cjs'
      },
      'moment': {
        format: 'cjs'
      }
    };
    

记得使用包括.js在内的完整路径,希望这可以帮到你 :)

我按照moment的方式做了同样的事情,来自文档:https://github.com/angular/angular-cli/wiki/3rd-party-libs


我今天一定会尝试这个。 - raju
请您告诉我,如果有任何需要我详细说明的事情。 - DNRN
运行 "typings install underscore --save --global" 命令时出现错误 "typings ERR! message Unable to find "underscore" ("npm") in the registry." - raju
不应该全局安装underscore。只需运行命令:npm install underscore --save。 - DNRN
再次出现这个错误:typings install underscore --save --global。 - raju
@raju 尝试一下,输入 typings install --save --global dt~underscore - Expert wanna be

0

我正在使用 Angular-cli,我所做的就是在 package.json 中添加这一行

"underscore": "^1.8.3",

然后我运行:
1. npm install underscore --save
2. npm install 然后它就可以工作了...

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接