Import existing AMD module into ES6 module - javascript

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

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.

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.

A few changes for the latest version of babel:
First, babel({"modules": "amd"}) doesn't work with the latest version of babel. Instead, use babel({"plugins": ["#babel/plugin-transform-modules-amd"]}). (You'll need to install that plugin as a separate module in npm, i.e. with npm install --save-dev #babel/plugin-transform-modules-amd.)
Second, the syntax for gulp.task no longer accepts arrays as its second argument. Instead, use gulp.parallel or gulp.series to create a compound task.
Your gulpfile will end up looking like this:
"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({"plugins": ["#babel/plugin-transform-modules-amd"]}))
.pipe(gulp.dest("build/js"));
});
gulp.task("default", gulp.parallel("copy", "compile-es6"));

Related

How do I import and use my transpiled Typescript library using SystemJS?

I have a TypeScript library that I've created. I need to know how to import and use this library in a browser. First, I am using tsc v2.1.4; I am also using gulp's TypeScript plugins to help with the development process. I have a gulp task that compiles my *.ts files to *.js files as follows.
gulp.task('dist', function() {
var tsResult =
gulp.src(['src/**/*.ts'])
.pipe(sourcemaps.init())
.pipe(tsc({ out: 'mylib.js', noImplicitAny: true, target: 'es6', sourceMap: true, module: 'system' }));
return tsResult.js
.pipe(sourcemaps.write())
.pipe(gulp.dest('dist'));
});
The generated mylib.js file looks something like the following.
System.register("vehicle/car",[], function(exports_1, context_1) {
"use strict";
var __moduleName = context_1 && context_1.id;
var Car;
return {
execute: function() {
Car = class Car {
constructor(make, model) {
this.make = make;
this.model = model;
}
};
exports_1("Car", Car);
};
});
I then attempt to follow the documentation on SystemJS and create a index.html to test usage.
<html>
<head>
<title>Test MyLib</title>
</head>
<body onload="start()">
<script src="node_modules/systemjs/dist/system.js"></script>
<script>
function start() {
SystemJS.import('dist/mylib.js')
.then(function(lib) {
console.log(lib);
//what do i do here? how do i use my classes/objects here?
});
}
</script>
</body>
</html>
Looking at the JavaScript console, I see no errors. Where I log the lib out, it is just an Object with a bunch of functions that I'm not sure how to use to instantiate the classes/objects from my library.
I'm continuing to read more on how this TypeScript to ES6 to ES5 stuff works. Apparently, even though I've generated a JavaScript file (e.g. mylib.js) I just can't simply reference it like
<script src="dist/mylib.js"></script>"
and then use it. I have to go through SystemJS (which I'm new to and is a part of the confusion). Apparently, it seems like I can just reference my *.ts files directly and use other plugins (babel) with SystemJS to transpile on the fly. It doesn't help that the documentation on babel systemjs plugin is out of date (the usage instructions is out of date it seems).
The SystemJS usage instructions are a bit confusing too. In some cases I see SystemJS.config({...}) and in some cases I see System.config({...}). I'm speculating they changed SystemJS from System, but I'm really not sure.
I'd appreciate clarification on how to go from a TypeScript library project all the way browser usage; any online examples or guidance on here is appreciated (and I'm continuing to search as well).

Run Jasmine tests written in TypeScript

I have a Typescript+Node+Angular2+Electron app and currently trying to run tests for node classes, written also in Typescript.
For building the application and running it within electron I use following tsconfig:
"compilerOptions": {
"module": "system",
"target": "es6",
...
}
So as you can see, it's using systemjs and compiling TS into JS-es6. It works fine, application itself is working.
Now I need Jasmine to come on board. I installed this npm package, updated my gulp tasks to run gulp-jasmine for just 1 file:
gulp.task('jasmine', function() {
gulp.src('./test/test.js')
.pipe(jasmine())
});
This is how my test.js looks like:
System.register(["./models-src/app/models/pathWatch/pathWatch"], function(exports_1, context_1) {
"use strict";
var __moduleName = context_1 && context_1.id;
var pathWatch_1;
return {
setters:[
function (pathWatch_1_1) {
pathWatch_1 = pathWatch_1_1;
}],
execute: function() {
describe("Run Application:", () => {
it("starts", () => {
var pw1 = new pathWatch_1.PathWatch();
expect(true).toEqual(true);
});
});
}
}
});
So, nothing special, 1 import-1test-1assert, wrapped with SystemJs stuff.
When I try to run this test, I have an error: "System is not defined".
My questions are:
1) Is it possible to run jasmine tests, using systemjs loader inside?
2) If it's possible, do I need to install/configure some additional stuff?
3) I tried to compile TS using Module="commonjs" and it's working. But I don't want to compile my source differently for tests and build. Why it's working fine with commonjs without any additional manipulations?
4) Also I tried to compile TS using Module="es6". It's not working, I have an error "Unexpected reserved word". Is it possible to run jasmine tests written in js es6 without transpiling them into es5?
Thanks a lot!
1) Is it possible to run jasmine tests, using systemjs loader inside?
2) If it's possible, do I need to install/configure some additional
stuff?
You mean, run jasmine tests in node using systemjs as a loader? I don't think jasmine supports using systemjs instead of require for loading modules. So your tests need to be in commonjs, but test code can use SystemJS to load and test application code. Something like this in test.js could work, provided that systemjs is configured properly and can find pathWatch module:
describe("Run Application:", () => {
it("starts", (done) => {
var system = require('systemjs');
system.config({
// systemjs config here
//
});
system.import('path-to-path-watch-module').then(pathWatch => {
var pw = new pathWatch.PathWatch();
expect(true).toEqual(true);
done();
});
});
});
system.import is asynchronous, so all jasmine tests need to be async too.
3) I tried to compile TS using Module="commonjs" and it's working. But
I don't want to compile my source differently for tests and build. Why
it's working fine with commonjs without any additional manipulations?
Because then there is no reference to System in the compiled code - it uses module.exports like any other node module and can be loaded as is by jasmine.
4) Also I tried to compile TS using Module="es6". It's not working, I
have an error "Unexpected reserved word". Is it possible to run
jasmine tests written in js es6 without transpiling them into es5?
Module="es6" requires a runtime that supports es6 import and export, so it needs a transpiler and module loader before it can run on current version of node.

gulp babel, exports is not defined

Consider the following example code (and maybe I am doing it wrong?)
var FlareCurrency = {
};
export {FlareCurrency};
I have the following task:
gulp.task("compile:add-new-currency-minified", function(){
return gulp.src('src/add-new-currency/**/*.js')
.pipe(babel())
.pipe(concat('Flare-AddNewCurrency.js'))
.pipe(uglify({"preserveComments": "all"}))
.pipe(gulp.dest('dist/minified/'));
});
When I run this I get the following:
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var FlareCurrency={};exports.FlareCurrency=FlareCurrency;
For the fun of it, I wanted to run it in the console, yes I know it does nothing but I didn't expect to see this:
Uncaught ReferenceError: exports is not defined(…)
The non minified version:
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var FlareCurrency = {};
exports.FlareCurrency = FlareCurrency;
throws the same error. Ideas?
That is not actually a babel issue, you are just trying to run CommonJS code (transpiled from ES6 export) in the browser without preparation. CommonJS doesn't run on the browser, you need to use a tool to package it for the browser, such as Webpack or Browserify.
Just by coincidence this week I created a small project on Github that shows a setup of Gulp + ES6 code (using export) + Babel + Webpack: gulp-es6-webpack-example.
In my example you can load JS code on the browser either synchronously (pre-loaded) or asynchronously (lazy-loaded).
I fix it just set se6 for settings gulp-typescript package:
import gulp from 'gulp';
import ts from 'gulp-typescript';
import uglify from 'gulp-uglify';
import browserSync from 'browser-sync';
export const scripts = () => {
return gulp.src(['app/scripts/*', '!app/scripts/modules/'])
.pipe(ts({
noImplicitAny: true,
target: "es6" // <<< THIS
}))
.pipe(uglify())
.pipe(gulp.dest('dist/scripts/'))
.pipe(browserSync.stream())
}
Besides you have to set type="module" for connect your js file in html.
<script type="module" src="scripts/index.js"></script>

Loading webpack module in a require.js based project returns null

I'm trying to load a library that compiles to Webpack in a require.js project. While the library exposes an object, it returns null when required from the require.js project :
define(function(require, exports, module) {
[...]
require("./ext/mylib.core.js"); // -> null
})
Is there any flags that I can use in Webpack to enable AMD compliance ? There are some references to AMD in the generated library but as it is it does not seem to do anything.
The solution was in Webpack documentation : there is an outputLibrary flag that can be set to "amd" or "umd" and in that case webpack produces amd compliant modules.
EDIT 3:/EDIT: 4
Webpack is not cooperating it may seem, so another possibility would be to expose the module with the shim config option:
require.config({
paths: {
// Tell require where to find the webpack thingy
yourModule: 'path/to/the/webpack/asset'
},
shim: {
// This lets require ignore that there is no define
// call but will instead use the specified global
// as the module export
yourModule: {
exports: 'theGlobalThatIsPutInPlaceByWebpack'
}
}
});
This obviously only works in the case that the webpack stuff is putting something in the global scope. Hope this helps!
EDIT 2:
So I got the question wrong as pointed out in the comments. I didn't find any built-in functionality to produce AMD modules from webpack - the end result seems to be a static asset js file. You could wrap the result in a
define(function () {
return /* the object that webpack produces */;
});
block, maybe with the help of some after-build event (e.g. using this after build plugin for webpack). Then you should be able to require the module with an AMD loader.
Original Answer:
require.js loads it's dependencies asynchronously, you have to declare them explicitly when you're not using the r.js optimizer or the like. So if the module exposes an AMD definition it should work like this:
// It works the way you did it ...
define(['path/to/your/module'], function (require, exports, module) {
require('path/to/your/module'); // -> { ... }
});
// ... but I personally prefer this explicit syntax + it is
// friendlier to a code minifier
define(['path/to/your/module'], function (yourModule) {
console.log(yourModule); // { ... }
});
Maybe you have to configure your require instance, there are docs for that.
EDIT1: as pointed out the way the module is being accessed is not wrong but the dependencies were missing, so I added code that is closer to the original question.

Testing CommonJS modules that use browserify aliases and shims

Browserify allows creating aliases and shimming modules that are not directly CommonJS compatible. Since I'd like to run my tests in node CLI, can I somehow handle those aliases and shimmed modules in node?
For example, let's say I'm aliasing ./my-super-module to supermodule and shimming and aliasing some jquery plugin ./vendor/jquery.plugin.js -> ./shims/jquery.plugin.shim.js to jquery.plugin.
As a result, I can do this in my module:
var supermodule = require('supermodule');
require('jquery.plugin');
// do something useful...
module.exports = function(input) {
supermodule.process(output)
}
Are there any practices how I could test this module in node.js/cli so that the dependencies are resolved?
You might want to use proxyquire if you plan to test this module directly in node using any cli runner.
using mocha will be something like this
describe('test', function () {
var proxyquire = require('proxyquire').noCallThru();
it('should execute some test', function () {
var myModule = proxyquire('./my-module', {
// define your mocks to be used inside the modules
'supermodule' : require('./mock-supermodule'),
'jquery.plugin': require('./jquery-plugin-mock.js')
});
});
});
If you want to test this is a real browser, you might not need to mock your aliases modules, you can use browserify to run your tests in karma directly.
If you need to mock modules in that scenario you can use proxyquireify, which will allow you to do the same but with browserify.
there is also browsyquire which is a fork of proxyquireify that I made with some extra features and a bug fix.

Categories