[英]How to concatenate several Javascript files into one file using Python
I would like to know how I can use Python to concatenate multiple Javascript files into just one file. 我想知道如何使用Python将多个Javascript文件连接为一个文件。
I am building a component based engine in Javascript, and I want to distribute it using just one file, for example, engine.js. 我正在用Javascript构建基于组件的引擎,我只想使用一个文件(例如engine.js)分发它。
Alternatively, I'd like the users to get the whole source, which has a hierarchy of files and directories, and with the whole source they should get a build.py Python script, that can be edited to include various systems and components in it, which are basically .js files in components/ and systems/ directories. 另外,我希望用户获得整个源,该源具有文件和目录的层次结构,对于整个源,他们应该获得一个build.py Python脚本,可以对其进行编辑以包含各种系统和组件。 ,它们基本上是components /和systems /目录中的.js文件。
How can I load files which are described in a list (paths) and combine them into one file? 如何加载列表(路径)中描述的文件并将它们组合为一个文件?
For example: 例如:
toLoad =
[
"core/base.js",
"components/Position.js",
"systems/Rendering.jd"
]
The script should concatenate these in order. 脚本应按顺序将它们连接起来。
Also, this is a Git project. 另外,这是一个Git项目。 Is there a way for the script to read the version of the program from Git and then write it as a comment at the beginning? 脚本是否可以从Git读取程序的版本,然后在开始时将其写为注释?
This will concatenate your files: 这将串联您的文件:
def read_entirely(file):
with open(file, 'r') as handle:
return handle.read()
result = '\n'.join(read_entirely(file) for file in toLoad)
You may then output them as necessary, or write them using code similar to the following: 然后,您可以根据需要输出它们,或使用类似于以下代码的方式编写它们:
with open(file, 'w') as handle:
handle.write(result)
How about something like this? 这样的事怎么样?
final_script = ''
for script_name in toLoad:
with open(script_name, 'r') as f:
final_script += ('\n' + f.read())
with open('engine.js', 'w') as f:
f.write(final_script)
You can do it yourself, but this is a real problem that real tools are solving more sophisticatedly. 您可以自己做,但这是一个真正的问题,实际工具正在更加复杂地解决。 Consider "JavaScript Minification", eg using http://developer.yahoo.com/yui/compressor/ 考虑“ JavaScript压缩”,例如使用http://developer.yahoo.com/yui/compressor/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.