Node: Merge ES6 JS modules to one .min.js file

Viewed 565

I created a small JS/CSS framework including custom elements some time ago. Now I want to improve my workflow (compiling, merging, minimizing ...) with npm and node.js, so I'm very new to this.

Each component (module) was written in a separate .js-file. There can be dependencies between one or more components, for instance:

File: src/modules/component_1.js

class Component_1{
    // Code ...
}
export{
    Component_1
}

File: src/modules/component_2.js

import {Component_1} from './component_1.js';
class Component_2{
    // Code ...
}
export{
    Component_2
}

What I want is a structure like this:

my-project/
|-- js/
|   |-- components.js 
|   |-- components.min.js
|-- src/
|   |-- modules/
|       |-- component_1.js
|       |-- component_2.js
|       |-- ...
|       |-- component_30.js
  • I want that my .js-files in src/modules/ stay untouched. So I can add new functions and so on using these files and after that I can create the new production .js-file js/components.min.js.
  • I want to realize it as a script, so that I can call it via console, for instance npm ruin build-js.
  • Step 1: Merging all .js modules to one file. So for that, all import statements from my modules must be removed.
  • Step 2: Compiling my ES6 modules to CJS (?).
  • Step 3: Save the result as js/components.js and js/components.min.js (minified).

I did a quit similar thing with my sass (compiling .scss into .css, .css.map, .min.css, .css.min.map using clean-css). But it seems that doing the same with my JS is quiet complicated for a node/npm beginner like me (using stand-alone uglify did not worked).

So how can I do this? There are a lot plugins and packages like webpack, rollup, uglify, grunt, gulp, yeoman and so one. But I definitly do not know which packages I exactly need.

EDIT: After some more hours of trying a solution with rollout and webpack, can anyone give an example how to do this? I think that it can not be that difficult to merge all js files from a directory and minify the result.

1 Answers

So you can use webpack to create js bundles, that is, you can mash your js files into one bundle. Webpack also have features that minify your code in production. You can learn more about webpack on its docs: https://webpack.js.org/concepts/ For special files, like sass files, you can use loaders, like sass-loader with style-loader and file loader.

Related