SystemJS是万能动态模块加载器

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')


上面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');

模块的格式会在System.register中自动探测。

加载ES6:
app/es6-file.js:


export class q {
constructor() {
this.es6 = 'yay';
}
}


System.import('app/es6-file').then(function(m) {
console.log(new m.q().es6); // yay
});

在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);
});