将下划线导入 Angular 2 CLI 项目

Import Underscore to Angular 2 CLI project

我已经使用 Angular CLI 工具开始了一个新项目。之后,我按照 this official guide 导入 Underscore 并按照它所说的那样 exactly

但是当我尝试在 app.component 中使用 Underscore 并显示错误消息时,我的项目仍然在浏览器中崩溃:

ORIGINAL EXCEPTION: ReferenceError: _ is not defined

dist/vendor 文件夹中添加了下划线,所以我猜测问题出在 Systemjs 配置中。

这是我的 angular-cli-build:

var Angular2App = require('angular-cli/lib/broccoli/angular2-app');

module.exports = function(defaults) {
  return new Angular2App(defaults, {
    sassCompiler: {
      includePaths: [
        'src/styles'
      ]
    },
    vendorNpmFiles: [
      'systemjs/dist/system-polyfills.js',
      'systemjs/dist/system.src.js',
      'zone.js/dist/**/*.+(js|js.map)',
      'es6-shim/es6-shim.js',
      'reflect-metadata/**/*.+(ts|js|js.map)',
      'rxjs/**/*.+(js|js.map)',
      'underscore/underscore.js',
      '@angular/**/*.+(js|js.map)'
    ]
  });
};

这是我的系统配置:

"use strict";

// SystemJS configuration file, see links for more information
// https://github.com/systemjs/systemjs
// https://github.com/systemjs/systemjs/blob/master/docs/config-api.md

/***********************************************************************************************
 * User Configuration.
 **********************************************************************************************/
/** Map relative paths to URLs. */
const map: any = {
  'underscore':                 'vendor/underscore/',
};

/** User packages configuration. */
const packages: any = {
  'underscore':                 { main: 'underscore.js', format: 'cjs' },
};

////////////////////////////////////////////////////////////////////////////////////////////////
/***********************************************************************************************
 * Everything underneath this line is managed by the CLI.
 **********************************************************************************************/
const barrels: string[] = [
  // Angular specific barrels.
  '@angular/core',
  '@angular/common',
  '@angular/compiler',
  '@angular/forms',
  '@angular/http',
  '@angular/router',
  '@angular/platform-browser',
  '@angular/platform-browser-dynamic',

  // Thirdparty barrels.
  'rxjs',

  // App specific barrels.
  'app',
  'app/shared',
  /** @cli-barrel */
];

const cliSystemConfigPackages: any = {};
barrels.forEach((barrelName: string) => {
  cliSystemConfigPackages[barrelName] = { main: 'index' };
});

/** Type declaration for ambient System. */
declare var System: any;

// Apply the CLI SystemJS configuration.
System.config({
  map: {
    '@angular': 'vendor/@angular',
    'rxjs': 'vendor/rxjs',
    'main': 'main.js'
  },
  packages: cliSystemConfigPackages
});

// Apply the user's configuration.
System.config({ map, packages });

我的app.component:

/// <reference path="../../typings/globals/underscore/index.d.ts" />

import { Component } from '@angular/core';

declare var _;

@Component({
  moduleId: module.id,
  selector: 'app-root',
  template: `<h1>{{title}}</h1>`
})
export class AppComponent {
  title = _.version;
}

我哪里出错了?

还有为什么这么复杂?社区会接受只添加一个简单的第三方库这么麻烦吗?

您的配置基本上设置 underscore 以便 SystemJS 可以在需要时找到它。

当你改变system-config.ts时,你告诉SystemJS:如果有人要求underscore,它是一个文件underscore.js,可以在 vendor/underscore/ 文件夹中找到 -- 其模块格式为 CommonJS (cjs).

angular-cli-build.js 的更改是为了告诉 angular-cli 它应该选择哪些文件并将其放入 vendor 文件夹。 (所以,如果你告诉 SystemJS 它会在那里找到下划线,这就是它在那里的原因。)

但仅此一项 不会 import/add 下划线进入您的应用程序的全局范围。

您必须在每个 .ts 文件中导入它,以便 SystemJS 将它添加到该模块的转译 .js 中。

代替这两行:

/// <reference path="../../typings/globals/underscore/index.d.ts" />
declare var _;

将此添加到您的文件中:

import * as _ from 'underscore';

如果遇到问题,请尝试检查在浏览器中执行的生成的 .js 源代码。在您的情况下,您可能会发现没有 require() 方法导入 underscore.

添加第 3 方库的 doco 具有误导性。 敲了一个多小时的脑袋!

declare var _; // this won't work.

你需要的是

/// <reference path="../../../typings/globals/underscore/index.d.ts" />
import * as _ from 'underscore';