简体   繁体   English

如何将npm模块编译为浏览器脚本?

[英]How to compile a npm module into a browser script?

I want to customize the Parse SDK. 我想自定义Parse SDK。 They provide source through an npm module , which makes it usable in node environments. 它们通过npm模块提供源,从而使其可在节点环境中使用。

How can I compile this node module into a standalone parse.js script which will run as it is on a browser? 如何将这个节点模块编译成一个独立的parse.js脚本,该脚本将在浏览器中运行?

I tried using browserify as 我尝试使用browserify作为

browserify ./parse -o parse.js

but the parse.js it spits out is quite large and still contains node remanents: process and require commands. 但是它吐出的parse.js很大,并且仍然包含节点剩余部分: processrequire命令。 Although it executes without any error on browser, the browser cannot find Parse definition. 尽管它在浏览器上执行时没有任何错误,但浏览器找不到Parse定义。

AFAIK, Parse-module doesn't expose itself as a browser global. AFAIK,解析模块不会将自身公开为全局浏览器。 You should have a file, such as app.js that contains your definitions and use that to require the Parse module. 您应该有一个文件,例如app.js ,其中包含您的定义,并使用该文件来要求Parse模块。

For example: 例如:

//app.js
var Parse = require("parse");
console.log(Parse)

Bundle it (the bundle will contain your app.js and the contents of the parse -module: 将其捆绑(捆绑将包含您的app.js和parse -module的内容:

browserify ./app.js -o app.bundle.js

and include the bundled file to your HTML file 并将捆绑的文件包含到您的HTML文件中

<script src="app.bundle.js"

After you open your HTML file, you should see the Parse object in your console. 打开HTML文件后,您应该在控制台中看到Parse对象。

Found the correct way to compile the parse npm module into a browser script is to use: 发现将解析npm模块编译成浏览器脚本的正确方法是使用:

browserify path/to/npm/parse --standalone parse > parse-browser.js

For any other script it should be : 对于其他脚本,应为:

browserify path_to_module --standalone global_name_to_expose > output.js

Also, since the parse node module has a lot of node code, I would recommend people to use envify followed by uglify to make their code more optimized. 此外,由于解析节点模块有很多节点代码,我会建议人们使用envify其次是丑化 ,使他们的代码更加优化。

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

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