Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I concatenate ES6 modules?

Tags:

How can I concatenate ES6 modules?

var foo = 2; // This would normally be scoped to the module. export function Bar() {}  // ...concatenate...  import { Bar } from 'javascripts/bar' //This file no longer exists in the concatenated scenario. export function Bam() {} 
like image 257
Ben Aston Avatar asked Dec 15 '14 16:12

Ben Aston


People also ask

How do ES6 modules work?

A module is nothing more than a chunk of JavaScript code written in a file. By default, variables and functions of a module are not available for use. Variables and functions within a module should be exported so that they can be accessed from within other files. Modules in ES6 work only in strict mode.

Are ES6 modules supported?

As ES6 refers to a huge specification and browsers have various levels of support, "Supported" means at least 95% of the spec is supported.

How many parts are there in an ES6 module?

The ES6 module standard has two parts: Declarative syntax (for importing and exporting) Programmatic loader API: to configure how modules are loaded and to conditionally load modules.


2 Answers

Update 2020-09-02: Esperanto was replaced by Rollup some time ago, and is a great choice for this problem. Depending on your needs, Webpack may also be a good choice.


If what you want to do is create a single JavaScript file that does not internally use ES6 modules, so that you can use it with browsers/node today, then I recommend using Esperanto (full disclosure, I'm a maintainer of the project). It allows you to create a bundle that concatenates all of the files together without the use of a loader like you'd get using something like browserify or webpack. This typically results in smaller code (no loader), better dead code elimination (when using a minifier like Google Closure Compiler or UglifyJS), and better performance as the JS interpreter is better able to optimize the result.

Here's an example usage, but note that there are plenty of tools to integrate Esperanto into your workflow:

var fs = require( 'fs' ); var esperanto = require( 'esperanto' );  esperanto.bundle({   base: 'src', // optional, defaults to current dir   entry: 'mean.js' // the '.js' is optional }).then( function ( bundle ) {   var cjs = bundle.toCjs();   fs.writeFile( 'dist/mean.js', cjs.code ); }); 

This example is taken from the wiki page on bundling ES6 modules.

like image 93
Brian Donovan Avatar answered Oct 02 '22 00:10

Brian Donovan


I would suggest that you take a look at http://webpack.github.io and then combine it with babel.

alternatively you can do it with babel alone:

https://babeljs.io/docs/usage/cli/

like image 25
Brian Demant Avatar answered Oct 02 '22 00:10

Brian Demant