如何编写模块化客户端Javascript? [英] How to write modular client-side Javascript?

查看:83
本文介绍了如何编写模块化客户端Javascript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个繁重的Javascript应用程序,最终将通过将一个脚本注入客户端网站来使用。

I am in the process of writing a heavy Javascript app, which will ultimately be used by injecting one script into clients websites.

截至目前,我正在编写所有内容一个JS文件中的模块,但我很快发现它是无效的,因为它感觉非常混乱和混乱,我觉得模块应该都在单独的文件中。

As of now I am writing all the modules in one JS file, however I am quickly finding that to be ineffective, as it feels very messy and cluttered, and I feel like the modules should all be in separate files.

我的问题是,管理这个问题的好方法是什么。我应该在单独的文件中编写所有应用程序模块,还是将它们编译成服务器上的一个?

My question is, what is a good approach to managing this. Should I write all the apps modules in separate files, and than compile them into one on the Server?

如果重要,我将Node.js用于我的服务器。

If it matters, I am using Node.js for my server.

推荐答案

第一点:不要尝试在一个文件中编码所有内容。大多数大型JavaScript应用程序包含许多文件。

First point : don't try to code everything in one file. Most big javascript applications contain dozens of files.

使用某种makefile来连接你的js(和css)文件。然后使用缩小器(我使用 Google Closure Compiler )。为了帮助调试,我的部署脚本总是并行创建两个版本:一个是非连接/缩小版本,另一个是连接/缩小版本。未压缩的版本支持现场开发/测试,无需任何部署操作。

Use some kind of makefile to concatenate your js (and css) files. And after that use a minifier (I use Google Closure Compiler). To help debug, my deployement scripts always make two versions in parallel : one non concatenated/minified and one concatenated/minified. The uncompressed version enables the development/test onsite without any deployement operation.

这意味着,对于所有大型应用程序开发,您需要某种部署工具链来协调操作。这可能基于shell脚本,maven,ant等。

This means that, as for all big application development, you need some kind of deployement toolchain to orchestrate the operations. This may be based on shell scripts, maven, ant, etc.

其次:使用类(没有滥用,javascript不是真正的OOP)和命名空间来清楚地隔离你的函数。

Secondly : use classes (without abuse, javascript isn't really OOP) and namespaces to clearly isolate your functions.

这篇关于如何编写模块化客户端Javascript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆