Import existing AMD module into ES6 module

2019-01-25 18:28发布

问题:

I have an existing application where I have AMD modules defined using RequireJS. I use "text" and "i18n" plugins for requirejs extensively in my project. I have been experimenting with ES6 modules lately and would like to use them while creating new modules in my application. However, I want to reuse the existing AMD modules and import them while defining my ES6 modules.

Is this even possible? I know Traceur and Babel can create AMD modules from ES6 modules, but that only works for new modules with no dependency on existing AMD modules, but I could not find an example of reusing the existing AMD modules.

Any help will be appreciated. This is a blocker for me right now to start using all ES6 goodies.

Thanks

回答1:

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.



回答2:

In addition to @Louis's answer, assuming you already have a bunch of third party libraries specified in require.js configuration, in your new ES6 modules, whenever you are importing a module, be it amd or es6, you'll be fine as long as you keep the imported module name consistent. For example:

Here is the gulpfile:

gulp.task("es6", function () {
  return gulp.src("modules/newFolder//es6/*.js")
  .pipe(babel({
    "presets": ["es2015"],
    "plugins": ["transform-es2015-modules-amd"] 
     // don't forget to install this plugin
  }))
  .pipe(gulp.dest("modules/newFolder/build"));
});

Here is the es6 file:

import d3 from 'd3';
import myFunc from 'modules/newFolder/es6module'
// ...

This will be compiled to sth like this:

define(['d3', 'modules/newFolder/es6module'], function (_d, _myFunc) {
  'use strict';
   // ...
});

as long as the module in define(['d3', 'modules/newFolder/es6module'], ... of the compiled file is fine in a original AMD file, it should work with under existing require.js setup, such as compress files etc.

In terms of @coderC's question about require.js loaders, I was using i18n!nls/lang in AMD modules, at first I thought it would be a really tricky thing to find an alternative of AMD plugin loaders in ES6 modules, and I switched to other localization tools such as i18next. But it turned out that it's okay to do this:

import lang from 'i18n!nls/lang';
// import other modules..

because it will be compiled by gulp task to sth like:

define(['d3', 'i18n!nls/lang'], function (_d, _lang) {
// ....

This way, we don't have to worry about the require.js loader.

In a nutshell, in ES6 modules, if you want to use existing AMD plugin/modules, you just need to ensure the compiled file is conformed with the existing setup. Additionally, you can also try the ES6 module bundler Rollup to bundle all the new ES6 files.

Hope this can be helpful for those who are trying to integrate ES6 syntax in project.