cod*_*erC 7 javascript module amd requirejs ecmascript-6
我有一个现有的应用程序,我使用RequireJS定义AMD模块.我在我的项目中广泛使用了"text"和"i18n"插件for requirejs.我最近一直在试验ES6模块,并希望在我的应用程序中创建新模块时使用它们.但是,我想重用现有的AMD模块并在定义我的ES6模块时导入它们.
这甚至可能吗?我知道Traceur和Babel可以从ES6模块创建AMD模块,但这仅适用于不依赖于现有AMD模块的新模块,但我找不到重用现有AMD模块的示例.
任何帮助将不胜感激.这对我来说是一个阻止我开始使用所有ES6好东西.
谢谢
是的,这是可以做到的。创建一个具有以下结构的新应用程序:
gulpfile.js
index.html
js/foo.js
js/main.es6
node_modules
Run Code Online (Sandbox Code Playgroud)
安装gulp并gulp-babel。(我更喜欢本地安装gulp,但您可能需要全局安装:这取决于您。)
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>
Run Code Online (Sandbox Code Playgroud)
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"]);
Run Code Online (Sandbox Code Playgroud)
js/foo.js:
define(function () {
return {
"foo": "the value of the foo field on module foo."
};
});
Run Code Online (Sandbox Code Playgroud)
js/main.es6:
import foo from "foo";
console.log("in main: ", foo.foo);
Run Code Online (Sandbox Code Playgroud)
运行gulp构建应用程序后,build/index.html在浏览器中打开该文件。您将在控制台上看到:
in main: the value of the foo field on module foo.
Run Code Online (Sandbox Code Playgroud)
ES6 模块main能够加载 AMD 模块foo并使用导出的值。也可以让原生 AMD 模块加载已转换为 AMD 的 ES6 模块。一旦 Babel 完成工作,就 AMD 加载器而言,它们都是 AMD 模块。