Ryan
Ryan

Reputation: 10101

How to bundle node.js library into my application?

For example,nock library,it is used as

var nock = require('nock');

I want to pack the whole library as a single JS file and distribute as part of my application that only require a basic node.js runtime.

From the lib folder, I see files:

common.js  delayed_body.js  intercept.js  match_body.js  mixin.js  recorder.js  request_overrider.js  scope.js

How to concat them and use as part of my program?

Upvotes: 0

Views: 1825

Answers (3)

cyperpunk
cyperpunk

Reputation: 702

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 will give you a executable file for your platform and it includes all your modules and doesn't require any seperate NodeJS installation.

Upvotes: 0

martin.code
martin.code

Reputation: 1311

This seems to be a task you can do with grunt. Grunt is a javascript task runner that runs tasks you specify. You can make a special task to scan the directory and take out all js files and concat them with the main script. I guess the problem might be to ensure that scripts are loaded in the right depenency order?

Upvotes: 0

kyldvs
kyldvs

Reputation: 61

You could use Browserify to bundle it and all it's dependencies.

browserify node_modules/nock/index.js -o bundle.js

Then you'll have a single file, bundle.js

Upvotes: 1

Related Questions