Yes, it can be done. Create a new application with the following structure:
gulpfile.js
index.html
js/foo.js
js/main.es6
node_modules
Install gulp
and gulp-babel
. (I prefer to install gulp
locally but you may want it globally: that's up to you.)
index.html
:
<!DOCTYPE html>
<html>
<head>
<title>Something</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.20/require.js"></script>
<script>
require.config({
baseUrl: "js",
deps: ["main"]
});
</script>
</head>
<body>
</body>
</html>
gulpfile.js
:
"use strict";
var gulp = require('gulp');
var babel = require('gulp-babel');
gulp.task("copy", function () {
return gulp.src(["./js/**/*.js", "./index.html"], { base: '.' })
.pipe(gulp.dest("build"));
});
gulp.task("compile-es6", function () {
return gulp.src("js/**/*.es6")
.pipe(babel({"modules": "amd"}))
.pipe(gulp.dest("build/js"));
});
gulp.task("default", ["copy", "compile-es6"]);
js/foo.js
:
define(function () {
return {
"foo": "the value of the foo field on module foo."
};
});
js/main.es6
:
import foo from "foo";
console.log("in main: ", foo.foo);
After you've run gulp
to build the application, open the file build/index.html
in your browser. You'll see on the console:
in main: the value of the foo field on module foo.
The ES6 module main
was able to load the AMD module foo
and use the exported value. It would also be possible to have a native-AMD module load an ES6 module that has been converted to AMD. Once Babel has done its work, they are all AMD modules as far as an AMD loader is concerned.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…