Skip to content

Instantly share code, notes, and snippets.

@bluepnume
Created April 3, 2016 04:45
Show Gist options
  • Save bluepnume/fcb54402053de758aa3a4a6b0b20f4bd to your computer and use it in GitHub Desktop.
Save bluepnume/fcb54402053de758aa3a4a6b0b20f4bd to your computer and use it in GitHub Desktop.
/*
Usage:
1. Place loader in a webpack loader directory
2. Add the following to webpack loader configuration:
{ test: /\.js/, loader: 'angular-es6-interop', exclude: /node_modules|jquery|angular(\.min)?\.js|\.build/}
*/
function findAll(regex, string, unique) {
regex = new RegExp(regex, 'g');
var matches = [];
while(true) {
var match = regex.exec(string);
if (!match)
break;
if (typeof match[1] !== 'undefined')
matches.push(match[1]);
else if (typeof match[0] !== 'undefined')
matches.push(match[0]);
else
break;
}
return matches;
}
function exportProviders(angular) {
angular && angular.exportProviders(module, exports, __dirname, __filename);
}
module.exports = function (content) {
this.cacheable && this.cacheable();
var registersAngularProviders = content.match(/\.(factory|service|provider|constant)\(/);
var registersES6Exports = content.match(/export (var|function|constant|class) \$\w+/);
if (registersAngularProviders && registersES6Exports) {
throw new Error('Can not register ES6 exports and angular providers in the same module. If in doubt, use ES6 exports and angular-es6-interop will auto-generate angular providers for you.');
}
if (registersAngularProviders && content.indexOf('angular.mock') === -1) {
return content.replace(/([,;]\s+)?(?:return\s+)?((var\s+\w+\s+=\s+)?(\w+\.)?module\()/g, '$1\n\n\n(' + exportProviders.toString() + ')(window.angular);\n\n\n$2');
}
if (registersES6Exports) {
var exp = findAll('export (?:var|function|constant|class) (\\$\\w+)', content);
return content + '\nangular.module()\n' + exp.map(function(providerName) {
return '.value("' + providerName + '", ' + providerName + ')';
}).join('') + ';';
}
return content;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment