html - 使用 Gulp 和缩小的 CSS/JS

标签 html css gulp

我最近开始使用 Gulp 来自动添加前缀、缩小 css 和缩小我的 JS。现在,所有获得自动前缀、缩小的文件都位于 dist 文件夹中。有没有一种方法可以将我的 html 文件指向这些缩小版本,而无需手动重新键入以下内容:

<script src="js/custom.js"></script>

到:

<script src="dist/custom.min.js"></script>

来来回回?

现在,当我开发时,我编辑了大约 5 到 10 个 css 和 JS 文件,但是当我编辑它们时,它显然是未缩小的、未自动添加前缀的版本。我敢肯定开发人员不是这样做的,所以我猜我遗漏了一个步骤......

最佳答案

你应该看看使用 source maps .来自那篇文章:

Basically it's a way to map a combined/minified file back to an unbuilt state. When you build for production, along with minifying and combining your JavaScript files, you generate a source map which holds information about your original files. When you query a certain line and column number in your generated JavaScript you can do a lookup in the source map which returns the original location. Developer tools (currently WebKit nightly builds, Google Chrome, or Firefox 23+) can parse the source map automatically and make it appear as though you're running unminified and uncombined files.

gulp-sourcemaps是你需要使用的。您没有提到您使用的是哪些 gulp 插件,但它们很有可能 have support for source maps .

这是一个简单的示例,说明您将如何使用它:

var gulp = require('gulp');
var minify = require('gulp-uglify');
var sourcemaps = require('gulp-sourcemaps');

gulp.task('minify', function() {
    gulp.src('src/*.js')
        .pipe(sourcemaps.init())    // Initialize the source maps.
        .pipe(minify())             // Do your minification, concatenation, etc.
        .pipe(sourcemaps.write())   // Write the source maps.
        .pipe(gulp.dest('dist'));   // Write the minified files.
});

只要确保原始未缩小的文件也由您的网络服务器提供服务器,以便浏览器可以下载它们。

这还有一个额外的好处,即当您在开发时测试您的网页时,您实际上是在运行您将最终部署的精简代码。

关于html - 使用 Gulp 和缩小的 CSS/JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35954689/

相关文章:

Gulp-watch 不接收新文件

javascript - gulp useref 不能处理多个 html 文件

html - 溢出中断内联显示

html - Flexbox 在 Safari 中设置错误的 iframe 高度

html - 谷歌字体 CSS 自定义

CSS继承问题

javascript - HTML5 视频 : autoplay not working in lightbox

html - 图像未覆盖整个 "div"区域

html - 在 Bootstrap 行中添加背景图像

gulp - Imagemin 不足以洞察 Google 页面速度?