Exporting a corners module as an es6 module
You have to wrap angularjs modules in IIFE according to the style guide we are using
https://github.com/johnpapa/angular-styleguide/tree/master/a1#iife
my-dir.js
(function() {
'use strict';
angular
.module('my.dir', [])
.controller('MyDirController', MyDirController),
.directive('my-dir', MyDirDirective);
function MyDirController() {
}
function MyDirDirective() {
return {
restrict: 'E',
controller: MyDirController
}
}
})();
app.js
(function() {
'use strict';
angular
.module('app', ['my.dir'])
})();
But since we are currently using webpack to bundle es6 modules. How should we use this IIFE and export
? We cannot do export default angular.module('my-dir', [])
how export should be a top-level command. Also, should we just return a string with the name of the module? So this can be included as a app
module app
. What's the best practice?
This works, but you have to re-enter the module name and it seems a little confusing having an export outside the IIFE (which I suppose should be the case)
(function() {
angular.module('my.dir', [])
.controller('MyDirController', MyDirController)
.directive('my-dir', MyDirDirective);
function MyDirDirective(appPath) {
return {
restrict: 'E',
scope: {},
bindToController: {},
controllerAs: '$ctrl',
template: '<div ng-bind="$ctrl.msg"></div>',
controller: MyDirController
};
}
function MyDirController() {
var self = this;
self.msg = "Hello World";
}
})();
export default 'my.dir'
source to share
After switching to modules, the new structure became
app.js
import myDir from './my-dir.js'
angular.module('app', [myDir.name]);
my-dir.js
// import template from './my-dir.html'; // Can use this with template property
export default angular.module('my.dir', [])
.controller('MyDirController', MyDirController)
.directive('my-dir', MyDirDirective);
function MyDirDirective() {
return {
restrict: 'E',
scope: true,
bindToController: {},
controllerAs: '$ctrl',
template: '<div ng-bind="$ctrl.msg"></div>',
controller: MyDirController
};
}
function MyDirController() {
const self = this; // Not needed if using arrow functions
self.msg = "Hello World";
}
IIFE is no longer required as everything is now a module by default if any javascript module system is always used
source to share