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

发布于 2024-07-09 06:47:07 字数 215 浏览 6 评论 0原文

我想为我的网站创建一个已编译的 JavaScript 文件。 对于开发,我更愿意将 JavaScript 保存在单独的文件中,并且作为我的自动化脚本的一部分,将文件连接成一个文件并对其运行压缩器。

我的问题是,如果我使用旧的 DOS 复制命令,它还会放入压缩器抱怨的 EOF 标记:

copy /A *.js generated.js /Y

其他人在做什么?

I want to create a compiled JavaScript file for my website. 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.

My problem is that if I use the old DOS copy command it also puts in the EOF markers which the compressor complains about:

copy /A *.js compiled.js /Y

What are other people doing?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

窝囊感情。 2024-07-16 06:47:07

我建议使用 Apache Ant 和 YUI Compressor。

http://ant.apache.org/

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

将类似的内容放入 Ant 构建 xml 中。
它将创建两个文件: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>

I recommend using Apache Ant and YUI Compressor.

http://ant.apache.org/

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

Put something like this in the Ant build xml.
It will create two files, application.js and 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>
若水般的淡然安静女子 2024-07-16 06:47:07

要在没有 EOF 的情况下进行复制,请使用二进制模式:

copy /B *.js compiled.js /Y

如果生成的文件仍然具有 EOF,则该文件可能来自原始文件之一,
它可以通过以下变体修复:

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

/A 从原始文件中删除尾部 EOF(如果有),/B 防止将 EOF 附加到结果文件中。 如果 EOF 不在末尾,则源文件将在此处被截断。 开关的顺序很重要。 如果您编写

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

- 源文件中的 EOF 将不会被删除,但仍然不会附加生成的 EOF。

自己尝试一下,这就是我得到的。 DOS命令很奇怪。

To copy without EOF use binary mode:

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:

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. If an EOF is not at the end, the source file will be truncated at it. 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.

Try it yourself, thats where I get it. DOS commands are weird.

淡忘如思 2024-07-16 06:47:07

在 asp.net AJAX 中,您可以使用“CompositeScript”标签。 这会将所有脚本合并到 1 个大 js 文件中,通过减少 http 304 和可能的 http 401 的数量来节省带宽。

示例:

 <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>

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

In asp.net AJAX, you can use the 'CompositeScript' tag. This will combile all your scripts into 1 big js file, saving bandwidth by reducing the number of http 304s and possibly http 401s.

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

迎风吟唱 2024-07-16 06:47:07

这是一个非常老的问题,但我想提一下,还有一些方法可以使用 javascript 连接 javascript! 显然是用nodejs...例如,有一些工具发布为npm模块,例如
这个 还有gruntgulp 插件也是如此。

我还想提一下一种非常非常有趣的技术,该技术正在 jQuery 和 Modernizr 等大型项目中使用。 这两个项目都是完全使用 requirejs 模块开发的,然后他们使用 requirejs 优化器 作为一个非常好的解决方案。智能串联器。 有趣的是,正如您所看到的,jQuery 和 Modernizr 都不需要 requirejs 才能工作,而发生这种情况是因为它们删除了 requirejs 语法仪式,以便摆脱代码中的 requirejs。 因此,他们最终得到了一个使用 requirejs 模块开发的独立库! 因此,除了其他优势之外,他们还能够对其库执行精简构建。 这里是一篇博客文章,解释了所有内容这个更详细。

This is a very old question, but I want to mention that there are also ways to concatenate javascript using javascript! with nodejs obviously... For example there are tools published as npm modules like
this and there are also grunt and gulp plugins too.

I also want to mention a very, VERY, interesting technique that is being used in huge projects like jQuery and Modernizr. Both of this projects are entirely developed with requirejs modules and then they use the requirejs optimizer as a very smart concatenator. 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. So they end up with a standalone library that was developed with requirejs modules!. Thanks to this they are able to perform cutsom builds of their libraries, among other advantages. Here is a blog post that explains all this more in detail.

预谋 2024-07-16 06:47:07

在你的机器上安装压缩器uglifyjs:

sudo npm -g install uglify-js

然后可以使用以下命令连接并压缩所有js文件。

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

Install the compressor uglifyjs on your machine:

sudo npm -g install uglify-js

Then the following command can be used to concatenate and compress all js files.

cat myAppDir/*.js | uglifyjs > build/application.js
淑女气质 2024-07-16 06:47:07

我们创建了一个由以下部分组成的机制:

  • 压缩(针对 js 和 css)
  • 缓存中的聚合(http 状态 304 之类的东西)
  • 在开发模式下发送原始文件

它可能无法满足您的需求,但为了回答您的问题询问其他人在做什么,其工作原理如下:

  1. 比如说,请求传入,
    /css.aspx?package=core
  2. 我们在 xml 配置文件中查找包名(其中
    例如声明
    包“core”包含文件
    /js/mootools.js 和
    /js/swfobject.js)
  3. 我们检查是否启用了缩小。 例如,在一个
    开发环境我们没有
    想要缩小的 js 内容是
    服务出来了,而是写下
    原始文件。 对于js来说这是完成的
    通过脚本的 document.writes
    包含,对于 css,我们编写导入规则。
  4. 如果需要缩小(在生产环境中),我们会检查请求中的 if-modified-since 标头。 如果该客户端已经具有缩小的内容,我们将发送 http 标头 304。如果客户端确实需要这些内容,我们会检查缓存中是否有缩小的内容并提供该内容。 否则,我们缩小并发送结果。

所有这些都被分解为单独的服务。 jsminificationwriter 服务中注入了一个缓存服务。 这利用了仅处理缩小规则的原始缩小服务。

这种方法的好处是:

  • 它迫使我们的开发团队以 js/css“包”的方式进行思考,从而正确地分割功能并将它们分布在需要它们的页面上。
  • 在开发过程中,您完全能够进行调试,获取正确的文件和行号。
  • 您可以连接任何其他缩小服务实现,例如 YUI 等。 JsMin 只是我们的第一次尝试。
  • 这是适用于不同内容类型的通用方法。

希望这可以帮助。 如果您愿意,我可以发布一些代码片段来进一步说明。

We have created a mechanism consisting of the following parts:

  • minfication (for js and css)
  • aggregation in packages
  • caching (http status 304 stuff)
  • 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
  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)
  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. For js this is done
    by document.writes of script
    includes, and for css we write import rules.
  4. If minification is required (in production env) we do a check on the if-modified-since header from the request. 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. 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. 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.
  • 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. JsMin was only our first take.
  • 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.

止于盛夏 2024-07-16 06:47:07

您还可以这样做:

type *.js > compiled.js

You can also do:

type *.js > compiled.js
昔梦 2024-07-16 06:47:07

我会第二个 yuicompressor,但我使用 /packer/

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

这对我来说真的非常好。

差↓一点笑了 2024-07-16 06:47:07

我知道这是一个非常老的问题,但为了完整起见,我将提到使用 Browserify 的选项。 它允许您使用 NPM 的 require 函数将项目构建为不同的模块来解决依赖关系,然后解决这些依赖关系并将整个项目连接到一个文件中。

例如,假设您的项目名为 FooBar,并且您想要输出名为 foobar.js 的文件。 您将创建一个 main.js 文件作为项目的入口点,需要包含所有应包含的模块。

main.js

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

然后运行:

browserify main.js -o foobar.js

或者,要在每次源文件更改时自动执行此操作,您也可以使用 Watchify

watchify main.js -o foobar.js

Browserify 还将解决模块之间的依赖关系。 例如,如果 doBar.js 依赖于 doQux.js...

doBar.js

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

那么 Browserify 将确保包含 doQux.jsfoobar.js 中,这样您就不会出现任何损坏的依赖关系。

I know this is a very old question, but for the sake of completeness I'll mention the option of going with 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.

For example, say your project is called FooBar and you want to output a file called 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

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 main.js -o foobar.js

Browserify will also resolve dependencies between modules. So for example, if doBar.js depends on doQux.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.

我的鱼塘能养鲲 2024-07-16 06:47:07

您还可以尝试wro4j(java的Web资源优化器),它可以用作构建工具(maven插件)、运行时解决方案(使用过滤器)或命令行工具。 它允许您轻松地组织资源并使用十几个机器人类型资源的压缩器为您处理合并:js 和 css。

定义要合并的资源很简单:

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

免责声明:我是该项目的提交者。

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. 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.

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.

贱贱哒 2024-07-16 06:47:07

这就是我使用 glob 解决相同任务的方法:

const fs = require('fs');
const glob = require('glob');

const outputFile = './output/output.js';
const filesToConcat = './path/*.js';

// delete output file if exists (otherwise it will continue appending)
fs.unlink(outputFile, function(err) {
  console.log('output.js is removed');
});

// concat all js files into cam-benefits-ui.js
glob(filesToConcat, function(err, files) {
  files.forEach(file => {
    fs.readFile(file, 'utf8', function(err, data){
      fs.appendFileSync(outputFile, data);
    });
  });
});

This is how I resolved the very same task using glob:

const fs = require('fs');
const glob = require('glob');

const outputFile = './output/output.js';
const filesToConcat = './path/*.js';

// delete output file if exists (otherwise it will continue appending)
fs.unlink(outputFile, function(err) {
  console.log('output.js is removed');
});

// concat all js files into cam-benefits-ui.js
glob(filesToConcat, function(err, files) {
  files.forEach(file => {
    fs.readFile(file, 'utf8', function(err, data){
      fs.appendFileSync(outputFile, data);
    });
  });
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文