在 Node 中合并和缩小 JS 文件

发布于 2024-11-17 20:34:23 字数 1807 浏览 0 评论 0原文

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

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

发布评论

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

评论(9

雨后咖啡店 2024-11-24 20:34:23

我建议使用 UglifyJS,它是 NodeJS 的 JavaScript 解析器/管理器/压缩器/美化器库。

如果您对不仅仅只是连接和缩小文件的自动化工具感兴趣,可以使用以下解决方案:

  • GruntJS 是一个用于 JavaScript 项目的基于任务的命令行构建工具。当前版本有以下内置任务:

    1. concat - 连接文件。
    2. init - 从预定义的模板生成项目脚手架。
    3. lint - 使用 JSHint 验证文件。
    4. min - 使用 UglifyJS 缩小文件。
    5. qunit - 运行 QUnit 在无头 PhantomJS 中进行单元测试实例。
    6. 服务器 - 启动静态网络服务器。

除了这些任务之外,还有很多可用的插件

  • Gulp 是一个工具包,可帮助您自动执行开发工作流程中痛苦或耗时的任务。对于 Web 开发(如果您喜欢的话),它可以通过执行 CSS 预处理、JS 转译、缩小、实时重新加载等来帮助您。所有主要 IDE 中都内置了集成,人们喜欢跨 PHP、.NET、Node.js、Java 等。 gulp 拥有超过 1700 个插件(还有很多不需要插件的功能),让您不再搞乱构建系统并重新开始工作。

  • Yeoman 是一组强大且固执己见的工具、库和工作流程,可以帮助开发人员快速构建美观、引人注目的网络应用程序。

    1. 闪电般的脚手架 - 使用可自定义的模板轻松搭建新项目(例如 HTML5 BoilerplateTwitter Bootstrap),AMD(来自 RequireJS )和更多。
    2. 自动编译CoffeeScript & Compass - 我们的 LiveReload 监视进程会在发生更改时自动编译源文件并刷新您的浏览器,因此您无需.
    3. 自动检查您的脚本 - 您的所有脚本都会自动针对 jshint 运行,以确保它们最好地遵循语言-实践。
    4. 内置预览服务器 - 不再需要启动您自己的 HTTP 服务器。我的内置程序只需一个命令即可启动。
    5. 出色的图像优化 - 我使用 OptiPNG 和 JPEGTran 优化您的所有图像,以便您的用户可以花更少的时间下载资产和更多时间使用您的应用。
    6. AppCache 清单生成 - 我为您生成应用程序缓存清单。只需建立一个项目即可繁荣。您将免费获得它。
    7. 杀手级构建过程 - 不仅可以缩小和串联,还可以实现压缩。我还优化了您所有的图像文件、HTML、编译您的 CoffeeScriptCompass 文件,为您生成应用程序缓存清单,如果您使用的是 AMD,我们将通过 r.js 传递这些模块,这样您就不必这样做。
    8. 集成包管理 - 需要依赖项吗?只需按一下键盘即可。我允许您通过命令行轻松搜索新包(例如,yeoman search jquery),安装它们并保留它们无需打开浏览器即可更新。
    9. 支持 ES6 模块语法 - 尝试使用最新的 ECMAScript 6 模块语法编写模块。这是一项实验性功能,可转换回 ES5,以便您可以在所有现代浏览器中使用该代码。
    10. PhantomJS 单元测试 - 通过 PhantomJS 在无头 WebKit 中轻松运行单元测试。当您创建新应用程序时,我还会为您的应用程序提供一些测试脚手架。

I recommend using UglifyJS which is a JavaScript parser / mangler / compressor / beautifier library for NodeJS.

If you are interested in automation tools that do more than simply concatenate and minify files, there are the following solutions:

  • GruntJS is a task-based command line build tool for JavaScript projects. The current version has the following built-in tasks:

    1. concat - Concatenate files.
    2. init - Generate project scaffolding from a predefined template.
    3. lint - Validate files with JSHint.
    4. min - Minify files with UglifyJS.
    5. qunit - Run QUnit unit tests in a headless PhantomJS instance.
    6. server - Start a static web server.

Besides this tasks there's a lot of plugins available.

  • Gulp is a toolkit that will help you automate painful or time-consuming tasks in your development workflow. For web development (if that's your thing) it can help you by doing CSS preprocessing, JS transpiling, minification, live reloading, and much more. Integrations are built into all major IDEs and people are loving gulp across PHP, .NET, Node.js, Java, and more. With over 1700 plugins (and plenty you can do without plugins), gulp let's you quit messing with build systems and get back to work.

  • Yeoman is a robust and opinionated set of tools, libraries, and a workflow that can help developers quickly build beautiful, compelling web apps.

    1. Lightning-fast scaffolding - Easily scaffold new projects with customizable templates (e.g HTML5 Boilerplate, Twitter Bootstrap), AMD (via RequireJS) and more.
    2. Automatically compile CoffeeScript & Compass - Our LiveReload watch process automatically compiles source files and refreshes your browser whenever a change is made so you don't have to.
    3. Automatically lint your scripts - All your scripts are automatically run against jshint to ensure they're following language best-practices.
    4. Built-in preview server - No more having to fire up your own HTTP Server. My built-in one can be fired with just one command.
    5. Awesome Image Optimization - I optimize all your images using OptiPNG and JPEGTran so your users can spend less time downloading assets and more time using your app.
    6. AppCache manifest generation - I generate your application cache manifests for you. Just build a project and boom. You'll get it for free.
    7. Killer build process - Not only do you get minification and concatenation; I also optimize all your image files, HTML, compile your CoffeeScript and Compass files, generate you an application cache manifest and, if you're using AMD, we'll pass those modules through r.js so you don't have to.
    8. Integrated package management - Need a dependency? It's just a keystroke away. I allow you to easily search for new packages via the command-line (e.g., yeoman search jquery), install them and keep them updated without needing to open your browser.
    9. Support for ES6 module syntax - Experiment with writing modules using the latest ECMAScript 6 module syntax. This is an experimental feature that transpiles back to ES5 so you can use the code in all modern browsers.
    10. PhantomJS Unit Testing - Easily run your unit tests in headless WebKit via PhantomJS. When you create a new application, I also include some test scaffolding for your app.
谜兔 2024-11-24 20:34:23

UglifyJS 是一个 Node 模块,主要用于缩小 JavaScript。我不认为它也可以连接文件,但我可能错过了一个选项。

编辑:
UglifyJS 2 中,它也内置了串联。

如果您想在节点应用程序中内联执行此操作,那非常简单。这允许您在运行时动态生成缩小/连接的 js 脚本,而无需使用 grunt 或 yeoman 方式。

npm install uglify-js

在你的模块中:

var fs = require('fs');
var uglify = require("uglify-js");

var uglified = uglify.minify(['file1.js', 'file2.js', 'file3.js']);

fs.writeFile('concat.min.js', uglified.code, function (err){
  if(err) {
    console.log(err);
  } else {
    console.log("Script generated and saved:", 'concat.min.js');
  }      
});

UglifyJS is a Node module that is all about minifying javascript. I don't think it also joins files, but there might be an option I missed.

Edit:
With UglifyJS 2, it has built in concatenation as well.

If you want to do this inline in your node app it's really easy. This allows you to dynamically generate your minified/concatenated js script at runtime without using the grunt or yeoman way.

npm install uglify-js

and in your module:

var fs = require('fs');
var uglify = require("uglify-js");

var uglified = uglify.minify(['file1.js', 'file2.js', 'file3.js']);

fs.writeFile('concat.min.js', uglified.code, function (err){
  if(err) {
    console.log(err);
  } else {
    console.log("Script generated and saved:", 'concat.min.js');
  }      
});
青春如此纠结 2024-11-24 20:34:23

如果您使用 Connect,那么我很幸运 Connect-Assetmanager

If you're using Connect, then I've had good luck with Connect-Assetmanager

半衾梦 2024-11-24 20:34:23

您最好使用 gulp / webpack 之类的东西来连接/组织/捆绑您的资产。


为了加入 js 文件,你可以像 twitter bootstrap makefile 中那样做,

cat js/bootstrap-transition.js js/bootstrap-alert.js js/bootstrap-button.js js/bootstrap-carousel.js js/bootstrap-collapse.js js/bootstrap-dropdown.js js/bootstrap-modal.js js/bootstrap-tooltip.js js/bootstrap-popover.js js/bootstrap-scrollspy.js js/bootstrap-tab.js js/bootstrap-typeahead.js > docs/assets/js/bootstrap.js

这只是文件的串联,并输出到 js 文件

然后你可以安装 uglify-js 来缩小 js:

npm -g install uglify-js

并使用你的路径/文件执行此命令.js ofc:

uglifyjs docs/assets/js/bootstrap.js -nc > docs/assets/js/bootstrap.min.js

正如 uglifyjs 2 以来的评论中提到的,你也可以这样做:

uglifyjs --compress --mangle -- input.js

You'll be better using something like gulp / webpack to concat/organize/bundle your assets.


In order to join js file you can do as its done in twitter bootstrap makefile

cat js/bootstrap-transition.js js/bootstrap-alert.js js/bootstrap-button.js js/bootstrap-carousel.js js/bootstrap-collapse.js js/bootstrap-dropdown.js js/bootstrap-modal.js js/bootstrap-tooltip.js js/bootstrap-popover.js js/bootstrap-scrollspy.js js/bootstrap-tab.js js/bootstrap-typeahead.js > docs/assets/js/bootstrap.js

This is just a concatenation of files with an output to a js file

Then you can install uglify-js to minify js:

npm -g install uglify-js

And perform this command with your path/file.js ofc:

uglifyjs docs/assets/js/bootstrap.js -nc > docs/assets/js/bootstrap.min.js

As mentioned in comments since uglifyjs 2 you could also do:

uglifyjs --compress --mangle -- input.js
别在捏我脸啦 2024-11-24 20:34:23

如果您喜欢 Rails 3.1 资产管道方法,您应该尝试我的 connect-assets 库。

If you like the Rails 3.1 asset pipeline approach, you should try my connect-assets library.

顾冷 2024-11-24 20:34:23

我绝对推荐闭包编译器的简单模式。

I'd definitely suggest the Closure Compiler's simple mode.

放肆 2024-11-24 20:34:23

也许不完全是你正在寻找的东西,但 Enderjs 可以工作。

Maybe not exactly what you're looking for but Enderjs could work.

耳根太软 2024-11-24 20:34:23

尝试这两个 Grunt 插件

https://www.npmjs.org/package/grunt-contrib -concat

https://www.npmjs.org/package/grunt-contrib-uglify

你可以像这样安装你需要的一切:

npm install grunt
npm install grunt-cli
npm install grunt-contrib-concat
npm install grunt-contrib-uglify

然后创建你的 grunt 文件,像这样:

Gruntfile.js

module.exports = function(grunt){
  grunt.initConfig({
    concat: {
      options: {
        process: function(src, path){
          return '\n/* Source: ' + path + ' */\n' + src;
        }
      },
      src: [
        '../src/**/*.js'
      ],
      dest: '../bin/app-debug.js'
    },
    uglify: {
      src: '../bin/app-debug.js',
      dest: '../bin/app.js'
    },
    watch: {
      options: {
        atBegin: true,
        event: ['all']
      },
      src: {
        files: '../src/**/*.js',
        tasks: ['concat']
      },
      dist: {
        files: '../bin/app-debug.js',
        tasks: ['uglify']
      },
    }
  }

  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-uglify');

  grunt.registerTask('default', ['watch']);
}

最后,在终端中输入 grunt ,Grunt 将开始监视 JavaScript 文件的更改,并自动连接和丑化它们(每当您将更改保存到 ../src/ 中的 js 文件时)

Try these two plugins for Grunt

https://www.npmjs.org/package/grunt-contrib-concat

https://www.npmjs.org/package/grunt-contrib-uglify

You can install everything you need like so:

npm install grunt
npm install grunt-cli
npm install grunt-contrib-concat
npm install grunt-contrib-uglify

Then create your grunt file, like so:

Gruntfile.js

module.exports = function(grunt){
  grunt.initConfig({
    concat: {
      options: {
        process: function(src, path){
          return '\n/* Source: ' + path + ' */\n' + src;
        }
      },
      src: [
        '../src/**/*.js'
      ],
      dest: '../bin/app-debug.js'
    },
    uglify: {
      src: '../bin/app-debug.js',
      dest: '../bin/app.js'
    },
    watch: {
      options: {
        atBegin: true,
        event: ['all']
      },
      src: {
        files: '../src/**/*.js',
        tasks: ['concat']
      },
      dist: {
        files: '../bin/app-debug.js',
        tasks: ['uglify']
      },
    }
  }

  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-uglify');

  grunt.registerTask('default', ['watch']);
}

Finally, type grunt in the terminal and Grunt will start watching your JavaScript files for changes and automatically concat and uglify them (whenever you save a change to your js files in ../src/

少女净妖师 2024-11-24 20:34:23

如果您已经有 uglify-js,您的代码将使用一些最新的 ES6 功能 (ECMAScript 2015 ) 并且它只是在第一次运行时返回解析错误,然后安装 uglify-es

npm install uglify-es -g

或者:

npm install mishoo/UglifyJS2#harmony

解释在 uglify-js-es6 包

这是一个临时包,包含最新版本的'harmony'分支 uglifyjs (UglifyJS2)。

您仍然可以使用 uglifyjs 命令正常运行它。压缩和重整示例:

uglifyjs -c -m -o js/es6stuff.js -- js/es6stuff/*.js

这将生成一个包含文件夹中所有 JS 文件的文件。双破折号 (--) 只是防止输入文件用作选项参数。

If you already have uglify-js, your code uses some of the latest ES6 features (ECMAScript 2015) and it just gave you back parse errors on the first run, then install uglify-es:

npm install uglify-es -g

Or:

npm install mishoo/UglifyJS2#harmony

The explanation is in uglify-js-es6 package:

This is a temporary package containing the latest release of the 'harmony' branch of uglifyjs (UglifyJS2).

You can still run it normally with the uglifyjs command. A compress and mangle example:

uglifyjs -c -m -o js/es6stuff.js -- js/es6stuff/*.js

Which will produce a single file with all the JS files of a folder. The double dash (--) just prevents input files being used as option arguments.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文