SystemJS 在 index.html 中导入 chart.js

SystemJS import chart.js in index.html

我是 angularjs 的新手(特别是 angularjs2)。

我对 SystemJS 导入/配置感到困惑。

我的应用程序 (angularjs2) 运行正常。我正在用 Visual Studio 开发它。

我已经设置了 package.json 加载 node_modules 我需要的东西。 就我而言,我想使用 chart.js

来自 package.json 文件的片段

"dependencies": {
    "angular2": "2.0.0-beta.15",
    "es6-shim": "^0.35.0",
    "reflect-metadata": "0.1.2",
    "rxjs": "5.0.0-beta.2",
    "systemjs": "^0.19.26",
    "zone.js": "0.6.11",
    "bootstrap": "3.3.6",
    "jquery": "2.2.3",
    "font-awesome": "4.5.0",
    "toastr": "2.1.2",
    "chart.js": "2.0.2"    
  },

在我的 Index.html 中,我有以下内容:

<!-- 2. Configure SystemJS -->
    <script>
        System.config({
            packages: {
                app: {
                    format: 'register',
                    defaultExtension: 'js'
                }
            }
        });

        System.import('app/main')
              .then(null, console.error.bind(console));

        $(document).ready(function () {
            window.toastr = toastr;
            setTimeout(function () {
                toastr.options = {
                    closeButton: true,
                    progressBar: true,
                    showMethod: 'slideDown',
                    timeOut: 2500
                };
                toastr.success('Welcome to the APP');

            }, 1300);
        });
    </script>

Chart JS 的导入方式:

 <!-- ChartJS-->
 <!--version1: OLD ChartJS importing WORKS ok--> 
 <!--<script src="scripts/plugins/chartJs/Chart.min.js"></script>-->

 <!--version2: This kind of importing does not work-->
 <script src="node_modules/chart.js/dist/Chart.min.js"></script>

注:

我有一个 toastr 也是从 node_modules 以这种方式导入的:

   <!-- Toastr -->
    <script src="node_modules/toastr/build/toastr.min.js"></script>

但它工作正常。

node_modules 文件夹未包含在我的解决方案中

我将在组件中使用它(稍后在单独的指令中 - 根据最佳方法)

在那一行

var myNewChart = new Chart(ctx).Line(lineData, options);

它正在抱怨:

ReferenceError: Chart is not defined
    at DashboardComponent.execute.DashboardComponent.createLinearChart

我将以这种方式在 SystemJS 中配置库,因为该库支持 CommonJS:

System.config({
  map: {
    chart: 'node_modules/chart.js/dist/Chart.js'
  },
  packages: {
    (...)
  }
});

这样您就可以导入 Chart 对象:

import Chart from 'chart';

(...)
var myNewChart = new Chart(...);

Chart.js版本发布后2.2.1Angular2 位于 RC4 可以按以下方式使用 chart.js

//package.json
"dependencies": {
    "@angular/common": "2.0.0-rc.4",
    "@angular/compiler": "2.0.0-rc.4",
    "@angular/core": "2.0.0-rc.4",
    "@angular/forms": "0.2.0",
    "@angular/http": "2.0.0-rc.4",
    "@angular/platform-browser": "2.0.0-rc.4",
    "@angular/platform-browser-dynamic": "2.0.0-rc.4",
    "@angular/router": "3.0.0-beta.2",
    "bootstrap": "3.3.7",

    "chart.js": "2.2.1",
    "...ETC"

从 node_modules 导入:

//Index.html
<script src="node_modules/chart.js/dist/Chart.js"></script>

实际使用:

this.chart = new Chart(ctx, { type: 'line', data: data, options: chartOptions });

有关 "How to use" 的更多详细信息,请参阅此 post: