3

I have a Node.js app with all modules written in CommonJS and some using es6 features such as generators, let, const etc. And this all works fine as is.

I want to bundle all these files into one file and then uglify that. My best guess at the necessary steps are: 1) Convert all modules to es6 modules - using Babel 2) Use rollup to create the bundle and output it as a CJS file. 3) Uglify this CJS file.

I've played with rollup & babel and have read articles such as https://duske.me/easy-es2015-compilation-with-rollup-js-and-gulp-js/ which works fine if the input modules are already es6 modules. And I've looked at https://github.com/rollup/rollup-plugin-babel but am floundering as I don't have much experience with babel, rollup etc.

2 Answers 2

1

I wouldn't try to convert CommonJS modules to ES6. It can be done (esnext is probably your best bet – I don't believe Babel has a plugin for going from CommonJS to ES6), but you might encounter some rough edges where the semantics of CommonJS don't quite match the semantics of ES6 modules.

Why not just write ES6 modules in the first place? That way, your app is more future-proof, and bundling will behave more predictably.

If that's not an option and your source files need to be CommonJS, you're probably better off using a CommonJS bundler such as Webpack or Browserify.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Rich. I currently have 31 files in CJS format which I'm reluctant to spend time & effort on refactoring into es6 modules (but may have to). For new code I am writing es6 modules and in the Browser I started using JSPM/System.js a few months ago after switching from Require.js and love it. I'll look at esnext which may be a good enough work-around for now. I'll also look at Webpack. Hopefully one day we'll get native es6 module support in node.js
0

This was possible with babel 5, but since babel 6 you need a plugin to use normal require('module') for CommonJS modules instead of "new" require('module').default

Here it the babel plugin for that: https://www.npmjs.com/package/babel-plugin-add-module-exports

2 Comments

Thanks, but I don't see how that helps me to convert from cjs into es6 modules.
you do not need to convert anything to get it working

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.