Last active
June 9, 2020 19:21
-
-
Save fastfrwrd/bf09d689d89d90ccd3fb to your computer and use it in GitHub Desktop.
evolution of modules when transitioning from RequireJS to Webpack + ES2015
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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