Skip to content

Instantly share code, notes, and snippets.

@fastfrwrd
Last active June 9, 2020 19:21
Show Gist options
  • Save fastfrwrd/bf09d689d89d90ccd3fb to your computer and use it in GitHub Desktop.
Save fastfrwrd/bf09d689d89d90ccd3fb to your computer and use it in GitHub Desktop.
evolution of modules when transitioning from RequireJS to Webpack + ES2015
// old-school RequireJS.
define(['module-a', 'module-b', 'jquery'], function(ModuleA, ModuleB, $) {
var result = {
a: new ModuleA(),
b: new ModuleB()
}
$('body').append(a.el);
return result;
});
// CommonJS sugar, RequireJS
define(function(require) {
// what's awesome about this is that if you have a linter
// like ESLint turned on to detect unused variables,
// it will notice unused dependencies in this syntax, where it cannot
// in the traditional requirejs syntax.
var ModuleA = require('module-a');
var ModuleA = require('module-b');
var $ = require('jquery');
var result = {
a: new ModuleA(),
b: new ModuleB()
}
$('body').append(a.el);
return result;
});
// once you've moved over to Webpack, you can easily transform your
// module into a CommonJS module. Delete the define block surrounding
// the module, and switch the return statement to use module.exports.
var ModuleA = require('module-a');
var ModuleA = require('module-b');
var $ = require('jquery');
var result = {
a: new ModuleA(),
b: new ModuleB()
}
$('body').append(a.el);
module.exports = result;
// if you're transpiling to ES2015, you can go one further and
// use ES2015 imports and exports for your dependencies. Just
// make sure to include one of the Babel plugins for modules
// in your Babel config, such as transform-es2015-modules-commonjs
import ModuleA from 'module-a';
import ModuleA from 'module-b';
import $ from 'jquery';
var result = {
a: new ModuleA(),
b: new ModuleB()
}
$('body').append(a.el);
export default result;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment