[英]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
? 我的意思是字面意思,不使用
require
和module.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.