简体   繁体   English

如何将 JavaScript 文件连接成一个文件?

[英]How do I concatenate JavaScript files into one file?

I want to create a compiled JavaScript file for my website.我想为我的网站创建一个已编译的 JavaScript 文件。 For development I would prefer to keep the JavaScript in separate files and just as part of my automated scripts concatenate the files into one and run the compressor over it.对于开发,我更愿意将 JavaScript 保存在单独的文件中,作为我的自动化脚本的一部分,将这些文件合并为一个文件并在其上运行压缩器。

My problem is that if I use the old DOS copy command it also puts in the EOF markers which the compressor complains about:我的问题是,如果我使用旧的 DOS 复制命令,它还会放入压缩器抱怨的 EOF 标记:

copy /A *.js compiled.js /Y复制 /A *.js 编译的.js /Y

What are other people doing?其他人在做什么?

I recommend using Apache Ant and YUI Compressor.我推荐使用 Apache Ant 和 YUI Compressor。

http://ant.apache.org/ http://ant.apache.org/

http://yui.github.com/yuicompressor/ http://yui.github.com/yuicompressor/

Put something like this in the Ant build xml.在 Ant 构建 xml 中放入类似的内容。 It will create two files, application.js and application-min.js.它将创建两个文件,application.js 和 application-min.js。

<target name="concatenate" description="Concatenate all js files">
    <concat destfile="build/application.js">
        <fileset dir="src/js" includes="*.js" />
    </concat>
</target>

<target name="compress" depends="concatenate" description="Compress application.js to application-min.js">
    <apply executable="java" parallel="false">
        <filelist dir="build" files="application.js" />
        <arg line="-jar" />
        <arg path="path/to/yuicompressor-2.4.2.jar" />
        <srcfile />
        <arg line="-o" />
        <mapper type="glob" from="*.js" to="build/*-min.js" />
        <targetfile />
    </apply>
</target>

To copy without EOF use binary mode:要在没有 EOF 的情况下进行复制,请使用二进制模式:

copy /B *.js compiled.js /Y

If the resulting file still has EOFs, that might have come from one of original files, it can be fixed by this variant:如果生成的文件仍有 EOF,这可能来自原始文件之一,则可以通过以下变体进行修复:

copy /A *.js compiled.js /B /Y

/A removes trailing EOFs from original files if any and /B prevents appending EOF to the resulting file. /A 从原始文件中删除尾随 EOF(如果有)和 /B 阻止将 EOF 附加到结果文件。 If an EOF is not at the end, the source file will be truncated at it.如果 EOF 不在末尾,源文件将被截断。 The order of switches is important.开关的顺序很重要。 If you write如果你写

copy /A *.js /B compiled.js /Y  

- EOFs in source files won't be removed but still resulting EOF won't be appended. - 源文件中的 EOF 不会被删除,但仍然不会附加生成的 EOF。

Try it yourself, thats where I get it.自己试试吧,这就是我得到它的地方。 DOS commands are weird. DOS 命令很奇怪。

In asp.net AJAX, you can use the 'CompositeScript' tag.在 asp.net AJAX 中,您可以使用“CompositeScript”标签。 This will combile all your scripts into 1 big js file, saving bandwidth by reducing the number of http 304s and possibly http 401s.这会将您的所有脚本合并到 1 个大 js 文件中,通过减少 http 304 和可能的 http 401 的数量来节省带宽。

Sample:样本:

 <asp:ScriptManager ID="ScriptManager1" runat="server">
        <CompositeScript>
            <Scripts>
                <asp:ScriptReference Path="~/Scripts/Script1.js" />
                <asp:ScriptReference Path="~/Scripts/Script2.js" />
                <asp:ScriptReference Path="~/Scripts/Script3.js" />
            </Scripts>
        </CompositeScript>
    </asp:ScriptManager>

For more info, see here: http://msdn.microsoft.com/en-us/library/cc488552.aspx有关更多信息,请参见此处: http : //msdn.microsoft.com/en-us/library/cc488552.aspx

This is a very old question, but I want to mention that there are also ways to concatenate javascript using javascript!这是一个非常古老的问题,但我想提一下,还有使用 javascript 连接 javascript 的方法! with nodejs obviously... For example there are tools published as npm modules like this and there are also grunt and gulp plugins too.使用 nodejs 显然......例如,有像这样的npm 模块发布的工具,也有gruntgulp插件。

I also want to mention a very, VERY, interesting technique that is being used in huge projects like jQuery and Modernizr.我还想提到一个非常非常有趣的技术,它被用于像 jQuery 和 Modernizr 这样的大型项目中。 Both of this projects are entirely developed with requirejs modules and then they use the requirejs optimizer as a very smart concatenator.这两个项目都是完全使用 requirejs 模块开发的,然后它们使用requirejs 优化器作为非常智能的连接器。 The interesting thing is that, as you can see, neither jQuery nor Modernizr needs on requirejs to work, and this happen because they erase the requirejs syntatic ritual in order to get rid of requirejs in their code.有趣的是,正如您所看到的,jQuery 和 Modernizr 都不需要 requirejs 才能工作,这是因为它们删除了 requirejs 语法规则,以便在代码中去掉 requirejs。 So they end up with a standalone library that was developed with requirejs modules!.所以他们最终得到了一个用 requirejs 模块开发的独立库! Thanks to this they are able to perform cutsom builds of their libraries, among other advantages.多亏了这一点,他们能够执行库的 cutom 构建,以及其他优势。 Here is a blog post that explains all this more in detail. 是一篇博客文章,更详细地解释了所有这些。

Install the compressor uglifyjs on your machine:在你的机器上安装压缩器 uglifyjs:

sudo npm -g install uglify-js

Then the following command can be used to concatenate and compress all js files.然后可以使用下面的命令来连接和压缩所有js文件。

cat myAppDir/*.js | uglifyjs > build/application.js

We have created a mechanism consisting of the following parts:我们创建了一个由以下部分组成的机制:

  • minfication (for js and css)缩小(用于 js 和 css)
  • aggregation in packages包中的聚合
  • caching (http status 304 stuff)缓存(http 状态 304 的东西)
  • sending out original files for in development mode在开发模式下发送原始文件

It may be too much for your needs, but as to answer your question what others do, here is how it works:这可能对您的需求来说太多了,但至于回答您的问题其他人是做什么的,以下是它的工作原理:

  1. A request comes in at, say, /css.aspx?package=core一个请求进来,比如说,/css.aspx?package=core
  2. We do a lookup of the packagename in a xml configuration file (which for instance declares that the package "core" contains the files /js/mootools.js and /js/swfobject.js)我们在 xml 配置文件中查找包名(例如声明包“core”包含文件 /js/mootools.js 和 /js/swfobject.js)
  3. We check if minification is enabled.我们检查是否启用了缩小。 For instance, in a development environment we don't want the minified js contents to be served out, but instead write the original files.例如,在开发环境中,我们不希望提供缩小后的 js 内容,而是编写原始文件。 For js this is done by document.writes of script includes, and for css we write import rules.对于 js,这是通过脚本包含的 document.writes 完成的,对于 css,我们编写导入规则。
  4. If minification is required (in production env) we do a check on the if-modified-since header from the request.如果需要缩小(在生产环境中),我们会检查请求中的 if-modified-since 标头。 If this client already has the minified contents, we send http header 304. If the client does require the contents, we check if we have minified contents in cache and serve that.如果这个客户端已经有缩小的内容,我们发送 http 头 304。如果客户端确实需要这些内容,我们检查缓存中是否有缩小的内容并提供服务。 Otherwise, we minify and send the result.否则,我们缩小并发送结果。

All this is broken up in separate services.所有这些都在单独的服务中分解。 There is a cache service injected in the jsminificationwriter service. jsminificationwriter 服务中注入了一个缓存服务。 This makes use of the original minificationservice that solely takes care of the minification rules.这利用了仅负责缩小规则的原始缩小服务。

What's nice in this approach is:这种方法的好处是:

  • It forces our development teams to think in js/css "packages" and therefore properly split up functionality and distribute them over the pages that require them.它迫使我们的开发团队在 js/css“包”中思考,因此正确地拆分功能并将它们分发到需要它们的页面上。
  • During development you are perfectly able to debug, getting proper files and line numbers.在开发过程中,您完全可以进行调试,获得正确的文件和行号。
  • You can hook up any other minification service implementation such as YUI and so forth.您可以连接任何其他缩小服务实现,例如 YUI 等。 JsMin was only our first take. JsMin 只是我们的第一次尝试。
  • It's a general approach that works for different content types.这是适用于不同内容类型的通用方法。

Hope this helps.希望这可以帮助。 I can post some code fragments to illustrate it more if you like.如果你愿意,我可以发布一些代码片段来说明它。

你也可以这样做:

type *.js > compiled.js

I'll second yuicompressor, but I use /packer/我将使用第二个 yuicompressor,但我使用 /packer/

http://johannburkard.de/blog/programming/javascript/automate-javascript-compression-with-yui-compressor-and-packer.html http://johannburkard.de/blog/programming/javascript/automate-javascript-compression-with-yui-compressor-and-packer.html

It's been really excellent for me.这对我来说真的很棒。

I know this is a very old question, but for the sake of completeness I'll mention the option of going with Browserify .我知道这是一个非常古老的问题,但为了完整起见,我会提到使用Browserify的选项。 It allows you to build your project as different modules using NPM's require function to resolve dependencies, and then it resolves those dependencies and concatenates your entire project into an single file.它允许您使用 NPM 的require函数将项目构建为不同的模块来解析依赖项,然后解析这些依赖项并将您的整个项目连接到一个文件中。

For example, say your project is called FooBar and you want to output a file called foobar.js .例如,假设您的项目名为FooBar,并且您想输出一个名为foobar.js的文件。 You'd create a main.js file as the entry point for the project, requiring all the modules that should be included.您将创建一个main.js文件作为项目的入口点,需要应包含的所有模块。

main.js主文件

require("./doFoo");
require("./doBar");

Then run:然后运行:

browserify main.js -o foobar.js

Or, to do it automatically every time a source file changes you could also use Watchify .或者,要在每次源文件更改时自动执行此操作,您也可以使用Watchify

watchify main.js -o foobar.js

Browserify will also resolve dependencies between modules. Browserify 还将解决模块之间的依赖关系。 So for example, if doBar.js depends on doQux.js ...例如,如果 doBar.js 依赖于doQux.js ...

doBar.js doBar.js

require("./doQux");
const doBar = ()=>{
    //Do some bar stuff.
}
exports.doBar = doBar;

Then Browserify will make sure to include doQux.js into foobar.js so that you won't have any broken dependencies.然后 Browserify 将确保将doQux.js包含到foobar.js以便您不会有任何损坏的依赖项。

You can also try wro4j (web resource optimizer for java), which can be used as a build tool (maven plugin), runtime solution (using filter) or command line tool.您还可以尝试wro4j (java 网络资源优化器),它可以用作构建工具(maven 插件)、运行时解决方案(使用过滤器)或命令行工具。 It allows you to easily keep resources organized and handle the merging for you using a dozen of compressors for resources of bot types: js and css.它允许您轻松地组织资源并为您处理合并,使用十几种压缩器来处理机器人类型的资源:js 和 css。

Defining resources to merge is easy as:定义要合并的资源很容易,因为:

<groups xmlns="http://www.isdc.ro/wro">
  <group name="all">
    <css>/asset/*.css</css>
    <js>/asset/*.js</js>
  </group>
</groups>  

Disclaimer: I'm a commiter of this project.免责声明:我是这个项目的提交者。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM