简体   繁体   English

将大型 node.js 应用程序捆绑到单个 .js 文件中

[英]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.我想将一个较大的 node.js cli 应用程序捆绑到一个 .js 文件中。 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 (eg browserify-http for http ).我可以使用 browserify 将整个内容捆绑到一个文件中,使用 main.js 作为入口点,但 Browserify 假设运行时环境是一个浏览器并替换它自己的库(例如, browserify-http代替http )。 So I'm looking for a browserify-for-node command所以我正在寻找一个browserify-for-node命令

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 .但是当我尝试运行$ 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.下面 JMM 的回答有效,但仅适用于我的机器。 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'

查看--node选项,以及它包含的其他更细粒度的选项。

You can use pkg by Zeit and follow the below steps to do so:您可以使用 Zeit 的 pkg 并按照以下步骤操作:

npm i pkg -g

Then in your NodeJS project, in package JSON include the following:然后在您的 NodeJS 项目中,在 JSON 包中包含以下内容:

"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.在 main 参数中写入要用作包入口点的文件名。

After that run the below command in the terminal of the NodeJS project之后在 NodeJS 项目的终端中运行以下命令

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

Or you can remove target parameter from above to build the package for Windows, Linux and Mac.或者您可以从上面删除目标参数来构建适用于 Windows、Linux 和 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此方法将为您提供可执行文件而不是单个 .js 文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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