SystemJS是萬能動態模組載入器

banq發表於2015-01-08
SystemJS:systemjs/systemjs · GitHub是一個通用Javascript模組載入器,可以在瀏覽器和NodeJS中載入ES6模組 AMD CommonJS 和全域性指令碼。

瀏覽器中使用:


  // Identical to writing System.baseURL = ...
  System.config({

    // set all requires to "lib" for library code
    baseURL: '/lib/',

    // set "app" as an exception for our application code
    paths: {
      'app/*': '/app/*.js'
    }
  });

  System.import('app/app')

<p class="indent">

上面app/app.js程式碼:

// relative require for within the package
  require('./local-dep');    // -> /app/local-dep.js

  // library resource
  var $ = require('jquery'); // -> /lib/jquery.js

  // format detected automatically
  console.log('loaded CommonJS');
<p class="indent">


模組的格式會在System.register中自動探測。

載入ES6:
app/es6-file.js:

export class q {
    constructor() {
      this.es6 = 'yay';
    }
  }
<p class="indent">


    System.import('app/es6-file').then(function(m) {
      console.log(new m.q().es6); // yay
    });
  
<p class="indent">


在NodeJS使用:首先安裝SystemJS:
npm install systemjs

載入模組類似瀏覽器:

var System = require('systemjs');

// loads './app.js' from the current directory
System.import('./app').then(function(m) {
  console.log(m);
});
<p class="indent">

相關文章