Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bundle a large node.js application into a single .js file

I would like to bundle a largish node.js cli application into a single .js file. My code is structured as follows:

|- main.js
|--/lib
|----| <bunch of js files>
|--/util
|----| <bunch of js files>
...etc

I can use browserify to bundle the whole thing into one file using main.js as the entry point, but Browserify assumes the runtime environment is a browser and substitutes its own libraries (e.g. browserify-http for http). So I'm looking for a browserify-for-node command

I tried running

$ browserify -r ./main.js:start --no-builtins --no-browser-field > myapp.js

$ echo "require('start') >> myapp.js

but I'm getting a bunch of errors when I try to run $ node myapp.js.

The idea is that the entire application with all dependencies except the core node dependencies is now in a single source file and can be run using

$ node myapp.js

Update

=============

JMM's answer below works but only on my machine. The bundling still does not capture all dependencies, so when I try to run the file on another machine, I get dependency errors like

ubuntu@ip-172-31-42-188:~$ node myapp.js
fs.js:502
  return binding.open(pathModule._makeLong(path), stringToFlags(flags), mode);
                 ^
Error: ENOENT, no such file or directory '/Users/ruchir/dev/xo/client/node_modules/request/node_modules/form-data/node_modules/mime/types/mime.types'
like image 934
yegodz Avatar asked Sep 26 '15 18:09

yegodz


1 Answers

You can use pkg by Zeit and follow the below steps to do so:

npm i pkg -g

Then in your NodeJS project, in package JSON include the following:

"pkg": {
"scripts": "build/**/*.js",
"assets": "views/**/*"
}
"main": "server.js"

Inside main parameter write the name of the file to be used as the entry point for the package.

After that run the below command in the terminal of the NodeJS project

pkg server.js --target=node12-linux-x64

Or you can remove target parameter from above to build the package for Windows, Linux and Mac.

After the package has been generated you have to give permissions to write:

chmod 777 ./server-linux

And then you can run it in your terminal by

./server-linux 

This method will give you can executable file instead of a single .js file

like image 153
cyperpunk Avatar answered Sep 18 '22 11:09

cyperpunk