Back to articles

How to copy required node modules to target dir with gulp?

One of the common tasks related to node.js development is building production ready package. Sometimes you just need to clean and install production only scripts, but sometimes you need something more complicated like preparing files for the electron package. And one of the important part is to copy the correct node modules to target locations. By correct node modules, I mean production dependencies without dev dependencies. Taking into account the complicated algorithm of node modules installation, it may be not a trivial task.

I have tried several approaches like reading package.json and extracting the list of dependencies, but in that case, you can’t just copy modules listed in dependencies, you have to copy dependencies recursively according to the algorithm. As for me, the most optimal solution is to give npm to deal with all modules by itself. The main idea is to install node modules with production parameters to some cache folder and then copy modules with every build to the target folder. To simplify calling of npm install I used gulp-install, but you can do everything with gulp-exec.

Here is my task’s configuration:

const gulp = require("gulp");
const ts = require("gulp-typescript");
const install = require("gulp-install");
// I need other info from package.json so let's load it as an object
const package = require("./package.json");

// Copy node modules from cache with cache refresh
gulp.task("node_modules", ["node_modules_cache"], () => {
gulp.src("./build/modules/node_modules/**/*.*", {base: "./build/modules/node_modules/"})
.pipe(gulp.dest("./build/debug/resources/app/node_modules"));
});

gulp.task("node_modules_cache", () => {
// Ensure the directory exists
if(!fs.existsSync("./build/modules")){
fs.mkdirSync("./build/modules");
}

// You can replace the following by just copying package.json, but I have already loaded it so let's just save
fs.writeFileSync("./build/modules/package.json", JSON.stringify(package));

// Make npm install in the cache location
return gulp.src("./build/modules/package.json")
.pipe(install({production: true}));
});

I’m trying to install scripts content and node_modules to ./build/debug/resources/app/ because I’m assembling the electron app at ./build/debug/. After that, I’m calling gulp-electron to prepare the final application and even change the icon of electron.exe file, but that is another story…

It also could be interesting to You

Requesting a lie

As a software developer and one who believes that people should not work, machines should work for them. I'm trying to automate everything I can in my business. Our team is now working on our…

WPF vs ElectronJS

Several days ago, we got the final results of a comparison of WPF and ElectronJS performance for one of our projects. The applications should load quite big files with data series and show all the…