复制到dist目录后,gulp更改html文件中的路径/链接

时间:2019-08-08 05:49:54

标签: gulp

我创建了一个静态网站,并且使用gulp进行自动化。现在,我也使用gulp pages将html文件复制到dist目录,但是当我检查该目录并打开任何html文件时,样式表和所有其他链接由于相对路径而损坏。将html复制到dist目录时,是否可以更改样式表和图像的路径?

gulpfile.js

"use strict";

const gulp = require("gulp");
const sass = require("gulp-sass");
const imagemin = require("gulp-imagemin");
const htmlmin = require("gulp-htmlmin");
const browserSync = require("browser-sync").create();
const sassPaths = ["./node_modules"];

function style() {
  return gulp
    .src("./app/scss/**/*.scss")
    .pipe(sass({ includePaths: sassPaths, outputStyle: "compressed" }))
    .pipe(gulp.dest("./app/dist/css"))
    .pipe(browserSync.stream());
}

function images() {
  return gulp
    .src("./app/images/**/*")
    .pipe(imagemin())
    .pipe(gulp.dest("/app/dist/images"));
}

function pages() {
  return gulp
    .src(["./app/**/*html"])
    .pipe(
      htmlmin({
        collapseWhitespace: true,
        removeComments: true
      })
    )
    .pipe(gulp.dest("./app/dist"));
}

function watch() {
  browserSync.init({
    server: {
      baseDir: "./app"
    }
  });
  gulp.watch("./app/scss/**/*.scss", style, images);
  gulp.watch("./app/**/*.html").on("change", browserSync.reload);
}

exports.style = style;
exports.images = images;
exports.pages = pages;
exports.watch = watch;

我想从

更改dist目录内的生成文件
<link rel="stylesheet" href="./dist/css/app.css">

<link rel="stylesheet" href="./css/app.css" />

1 个答案:

答案 0 :(得分:1)

看看gulp-processhtml或类似的软件包,例如gulp-useref

然后在您的html文件中,您将得到类似的内容:

<!-- build:css ./css/app.css -->
<link rel="stylesheet" href="./dist/css/app.css">
<!-- /build -->

这会将您的链接更改为<link rel="stylesheet" href="./css/app.css" />

const modifyHTMLlinks = require("gulp-processhtml");  // or try gulp-useref

function pages() {
  return gulp
    .src(["./app/**/*html"])
    .pipe(modifyHTMLlinks())
    .pipe(
      htmlmin({
        collapseWhitespace: true,
        removeComments: true
      })
    )
    .pipe(gulp.dest("./app/dist"));
}