使用Systemjs加载angular2依赖项

时间:2016-06-20 14:04:49

标签: angular systemjs

我已经在官方网站上学习了一段时间。由于SystemJS似乎是推荐的模块加载器,我正在尝试使用它。 从官方快速入门(https://angular.io/guide/quickstart)可以找到以下index.html示例加载angular2项目:

<html>
  <head>
    <title>Angular 2 QuickStart</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="styles.css">
    <!-- 1. Load libraries -->
     <!-- Polyfill(s) for older browsers -->
    <script src="node_modules/core-js/client/shim.min.js"></script>
    <script src="node_modules/zone.js/dist/zone.js"></script>
    <script src="node_modules/reflect-metadata/Reflect.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>
    <!-- 2. Configure SystemJS -->
    <script src="systemjs.config.js"></script>
    <script>
      System.import('app').catch(function(err){ console.error(err); });
    </script>
  </head>
  <!-- 3. Display the application -->
  <body>
    <my-app>Loading...</my-app>
  </body>
</html>

我想用systemJS加载所有东西,达到这种情况:

<html>
  <head>
    <title>Angular 2 QuickStart</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="styles.css">
    <!-- 2. Loading SystemJS -->
    <script src="node_modules/systemjs/dist/system.src.js"></script>
    <!-- 2. Configure SystemJS -->
    <script src="systemjs.config.js"></script>
    <script>
      System.import('app').catch(function(err){ console.error(err); });
    </script>
  </head>
  <!-- 3. Display the application -->
  <body>
    <my-app>Loading...</my-app>
  </body>
</html> 

这可能吗?

1 个答案:

答案 0 :(得分:0)

我建议您使用 angular-cli https://github.com/angular/angular-cli)来帮助您生成新项目并为您完成所有配置和辛勤工作。它会帮助你很多,你会节省相信我的时间。现在情况正在发生很大的变化,所以你在旅程中拥有像angular-cli这样的好朋友会更容易。

如果您不想使用它,您可以创建一个类似 system-config.js 的文件,其中包含类似的内容,您可以添加您想要的 对象特定库:

var map = {};
/** User packages configuration. */
var packages = {};

var barrels = [
    // Angular specific barrels.
    '@angular/core',
    '@angular/common',
    '@angular/compiler',
    '@angular/http',
    '@angular/router',
    '@angular/platform-browser',
    '@angular/platform-browser-dynamic',
    // Thirdparty barrels.
    'rxjs',
    // App specific barrels.
    'app',
    'app/shared',
];
var cliSystemConfigPackages = {};
barrels.forEach(function (barrelName) {
    cliSystemConfigPackages[barrelName] = { main: 'index' };
});
// 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: map, packages: packages });

然后在index.html文件中,您可以:

<script>
  System.import('system-config.js').then(function () {
    System.import('app');
  }).catch(console.error.bind(console));
</script>
相关问题