2

我正在使用gulp useref替换/合并我的index.html文件minify。当我传递路径时,我可以让 useref 工作,但是当我没有定义路径时,我希望它保持文件的原始路径。我知道我可以通过并将构建路径注释添加到每个文件,或者我可以运行一个任务来缩小所有其他文件。如果 useref 可以输出原始路径,那么这似乎是疯狂和毫无意义的,那么这个任务就可以完成这一切。

示例 - 注意剥离的代码,例如 aka rel=""。

HTML 文件

<!-- build:css I want this to return original path into my new "dist" folder. -->
    <link href="fonts/map/map.css">
    <link href="layout/item/item.css">
<!-- endbuild -->

this works bc path is defined and the files exist in the same folder.
<!-- build:css styles/combined.css -->
    <link href="styles/style.css">
    <link href="styles/color.css">
<!-- endbuild -->

吞咽任务

gulp.task('css', function () {
        return gulp.src('index.html')
            .pipe(useref())
            .pipe(minifyCss())
            .pipe(gulp.dest('dist'));
    });

生成的 HTML - index.html 文件被输出到 " dist" 文件夹并且.css filesminified. 这一切都有效,但注意到在href = "replace"路径的注释中没有定义 bc,并且在 dist 文件夹中输出了一个名为 undefined 的文件:

<link href="replace">
<link href="css/combined.css">

我想要的是...

<link href="fonts/map/map.css">
<link href="layout/item/item.css">
<link href="css/combined.css">
4

1 回答 1

0

我有同样的问题。我发现这是因为gulp-userefbaseVinyl 文件的属性设置为文件的父目录。幸运的是,这可以通过自定义插件轻松更改:

// other imports...
const through = require('through2');

function useRefTask() {
    return src('.tmp/**/*.html')
    .pipe(useref())
    .pipe(through.obj((file, _, cb) => {
        file.base = path.join(process.cwd(), "src"); // Change to whatever your input directory is.
        cb(null, file);
    })
    // rest of the pipeline...
}

注意:dest使用该relative属性来确定它将写入文件的位置,因此值得查看并确保它保留目录结构。

于 2020-04-12T04:02:29.210 回答