简体   繁体   English

使用node.js时如何在客户端和服务器端导入javascript代码?

[英]How to import javascript code both on the client and on the server side when using node.js?

I have a couple of Javascript functions I need to use both on the server side and on the client side in a node application. 我有几个Javascript函数,我需要在节点应用程序的服务器端和客户端使用它们。

On the server side, I could create a module and require it. 在服务器端,我可以创建一个模块并require它。 I would need to module.exports my functions. 我需要module.exports我的函数。 Unfortunately, I could not use that code module on the client side, because there is no such thing as require on the client side. 不幸的是,我无法在客户端使用该代码模块,因为在客户端没有require这样的东西。

I don't want to maintain the (nearly) same code in two version of the files. 我不想在两个版本的文件中维护(几乎)相同的代码。 Is there a standard/safe way to import Javascript code in a node module? 是否有标准/安全的方法来导入节点模块中的Javascript代码? I mean literally, without using require and module.exports ? 我的意思是字面意思,不使用requiremodule.exports Or is there another solution to my issue? 或者我的问题有另一种解决方案吗?

您正在寻找browserify ,它允许您在浏览器中使用require()module.exports运行Node- module.exports模块。

I have used browserify in the past. 我过去使用过browserify。 It allows you to use common.js style require syntax on the client side. 它允许您在客户端使用common.js样式需要语法。 A word of warning, you will probably have to use a single client side entry point, and therefore re-write a lot of your client side code. 一句警告,您可能必须使用单个客户端入口点,因此重新编写了许多客户端代码。

Here's the link - borwserify 这是链接 - borwserify

I'm sure I've seen Ember implement its own require method but I can't find any documentation for it. 我确定我已经看到Ember实现了自己的require方法,但我找不到任何文档。

On the way I saw http://www.requirejs.org which creates its own new require method which works which both the browser and nodejs. 在途中我看到了http://www.requirejs.org ,它创建了自己的新的require方法,它同时适用于浏览器和nodejs。

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

相关问题 如何使用服务器端代码和客户端代码编写node.js Web应用程序? - How should I go about writing a node.js web application with both server and client side code? 如何使用来自 javascript(客户端)的变量从 node.js(服务器端)检索数据? - How to retrieve data from node.js (server side) using a variable from javascript (client side)? 如何使用客户端JavaScript将数据发送到Node.js服务器 - How to send data to a node.js server using client side javascript 获取客户端javascript代码中可用的node.js服务器端对象 - Get node.js server-side object available in client-side javascript code 使用 Adob​​e Dreamweaver 时如何禁用“Node.js:服务器端 JavaScript”的自动启动? - How to disable auto-start of “Node.js: Server-side JavaScript” when using Adobe Dreamweaver? JavaScript验证在客户端和Node.js服务器上都有效吗? - JavaScript validation that works both on client and Node.js server? 客户端到服务器端Node.js - Client Side to Server Side Node.js 在客户端重用javascript代码(node.js,快速) - Reuse javascript code on client side (node.js, express) 使用Jasmine和node.js测试客户端javascript代码 - Testing client-side javascript code with Jasmine and node.js 使用Node.js在服务器端保存客户端数据 - Saving client data on the server side using Node.js
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM