In this post I will show how to combine ES2015 and CommonJS modules in the same bundle using the Closure Compiler.
In the following example I have created CarService as an ES2015 module, and CountryService as a CommonJS module.
In main.js I import both before compiling my application with the Closure Compiler.
As you can tell we have a combination of require statements for CommonJS, and import statements for ES2015.
Closure lets us combine both formats by specifying a few simple configuration parameters.
In this sample I am using the Java version of the Closure compiler.
To tell the compiler to expect both CommonJS and ES2105 I specify the process_common_js_modules flag and set language_in to ES6_Strict.
Closure will bundle both formats into to a single file that looks like this:
The final output is reduced to a console.log statement per service call.
In the final bundle Closure flattened the original module format. There is no longer any module specific syntax in the code.
I have put the code on Github in case you are interested in checking it out.