简体   繁体   中英

Bundle CommonJS files for Node.js

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM