简体   繁体   English

如何使用gulp重命名index.html中脚本的原始文件?

[英]How to rename the original files of scripts in index.html using gulp?

I've written a gulp task to rename files so that they can be versioned. 我编写了一个gulp任务来重命名文件,以便可以对其进行版本控制。 The problem is that the filenames of the files that the index.html scripts reference are not changed. 问题在于index.html脚本引用的文件的文件名没有更改。

For example, in my index.html : 例如,在我的index.html

<script src=pub/main_v1.js"></script>

But if you actually navigate through the build folder to the subdirectory pub , you will find main.js . 但是,如果您实际上在build文件夹中导航到子目录pub ,则会找到main.js

Here is the custom gulp task: 这是定制的gulp任务:

const gulpConcat = require('gulp-concat');
const gulpReplace = require('gulp-replace');
const version = require('./package.json').version;

gulp.task('version', function () {
    var vsn = '_' + version + '.js';
    gulp.src('scripts/**/*.js')
        .pipe(gulpConcat(vsn))
        .pipe(gulp.dest('./prodBuild'));

    return gulp.src('./prodBuild/index.html', { base: './prodBuild' })
        .pipe(gulpReplace(/* some regex */, /* append vsn */))
        .pipe(gulp.dest('./prodBuild'));
});

What do I need to fix/add so that the original filename changes to match that in the script tag? 我需要修复/添加什么以便原始文件名更改为与script标签中的文件名匹配?

Note: According to the gulp-concat docs , I should be able to find the concated files at prodBuild/[vsn] , where [vsn] is _v1.js . 注意:根据gulp-concat 文档 ,我应该能够在prodBuild/[vsn]找到prodBuild/[vsn]文件,其中[vsn]_v1.js However, it is no where to be found. 但是,在哪里都找不到。

Update: The files rename properly in index.html , but I can't seem to get the renaming of the original files to work. 更新:这些文件在index.html正确重命名,但是我似乎无法重命名原始文件。 Here's a snapshot of my build directory: 这是我的构建目录的快照:

prodBuild/
 pub/
   main.js
 someDir/
   subDirA/
     // unimportant stuff
   subDirB/
     file2.js
   file3.js
 // ...other files and folders...

EDIT: The issue is that you return only one of the two tasks. 编辑:问题是您只返回两个任务之一。 The first task is simply ignored by gulp, since it is not returned. gulp会简单地忽略第一个任务,因为它不会返回。 A simple solutions: Split it into two tasks, and reference the one from the other, like in this SO answer . 一个简单的解决方案:将其拆分为两个任务,然后像另一个SO回答中那样相互引用。

Old Answer 旧答案

This looks like a perfect case for the gulp-rename . 对于gulp-rename来说,这似乎是一个完美的案例。 You could simply pipe your scripts through gulp-rename , like this: 您可以简单地通过gulp-rename传递脚本,如下所示:

.pipe(rename(function (path) {
    path.basename += vsn;
    path.extname = ".js"
  }))

Gulp concat is, AFAIK, made for the concatination of files , not particularly for the renaming of them. Gulp concat是AFAIK,用于隐藏文件 ,而不是专门用于文件重命名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM