我有一个现有的应用程序,其中我使用 RequireJS 定义了 AMD 模块。我在我的项目中广泛使用 requirejs 的“text”和“i18n”插件。 我最近一直在试验 ES6 模块,并希望在我的应用程序中创建新模块时使用它们。但是,我想重用现有的 AMD 模块并在定义我的 ES6 模块时导入它们。
这可能吗?我知道 Traceur 和 Babel 可以从 ES6 模块创建 AMD 模块,但这只适用于不依赖于现有 AMD 模块的新模块,但我找不到重用现有 AMD 模块的示例。
任何帮助将不胜感激。这是我现在开始使用所有 ES6 好东西的障碍。
谢谢
最佳答案
是的,这是可以做到的。创建具有以下结构的新应用程序:
gulpfile.js
index.html
js/foo.js
js/main.es6
node_modules
安装 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>
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);
运行 gulp
构建应用程序后,在浏览器中打开文件 build/index.html
。您会在控制台上看到:
in main: the value of the foo field on module foo.
ES6 模块 main
能够加载 AMD 模块 foo
并使用导出的值。也可以让原生 AMD 模块加载已转换为 AMD 的 ES6 模块。一旦 Babel 完成它的工作,就 AMD 加载器而言,它们都是 AMD 模块。
关于javascript - 将现有的 AMD 模块导入 ES6 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32805234/