Node.js 可重用代码服务器-客户端
我正在 Node.js 上进行一些研发,到目前为止我很喜欢它,我只是好奇如何重用代码以便在客户端和服务器之间共享一些代码。
我使用 npm 安装的 Backbone.js 就是一个很好的例子。
目前我有一个如下所示的目录:
app.js
public/
routes/
views/
node_modules/
tests/
显然我使用express.js并且我所有的客户端代码都位于public
文件夹下,其中css
,images,
js
文件位于。
那么我如何才能在主干中拥有一个可以在服务器和后端使用的模型呢?
另外,我曾经使用 JavaScript AMD 和 Require.js 来构建和模块化我的应用程序,我已经习惯了它并且我倾向于喜欢它,我看到 require.js 可以通过 npm 获得,但现在我安装了它,我不再使用它确定我如何在客户端使用它,因为我曾经有这样的东西:
谢谢
I'm doing some R&D on Node.js and so far I like it, I'm just curious on how I could re-use code in order to have some shared code between client and server.
A good example of that need would be Backbone.js which I installed with npm.
Currently I have a directory that looks like this:
app.js
public/
routes/
views/
node_modules/
tests/
Obviously I use express.js and all my client-side code is under public
folder where css
, images
, js
files are located.
So how I could have a model in backbone which I could use it in both server and back?
Also I used to use JavaScript AMD with Require.js in order to structure and modulize my application, I got used to it and I tend to like it I saw require.js is available via npm but now that I installed it I'm not sure how I cal use it in client-side since I used to have something like this: <script data-main="js/main" src="js/libs/Require/require.js">
but since require.js is installed via npm it is isn't under public folder so I can't see any possible way to load it.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以将符号链接 (ln -s) 添加到 public 文件夹中的 require.js 中。
我认为你也可以将主干模型放在公共环境中,然后在服务器和客户端上使用 requirejs 来加载相同的文件。
You could add a symbolic link (ln -s) to require.js from the public folder.
I think you can just place the backbone model in public as well and then use requirejs both on the server and the client to load the same file.
我想这有点晚了,但我只是想补充一点,您可以使用 https,而不是在客户端使用 browserify ://npmjs.org/package/define 在服务器端,它允许您以 AMD 风格定义模块,但需要使用节点的 require()
I guess this is somewhat late, but I just wanted to add that instead of using browserify on the client side, you can use https://npmjs.org/package/define on the server side, which lets you define modules in AMD-style, but require them with node's require()