9

我尝试设置 gulp-inject 以将依赖项注入 index.html。一切正常,除了变换功能。我需要用以下方式替换部分文件路径:/frontend/src/->/static/我试过这样做(从某处复制粘贴):

transform : function ( filePath, file, i, length ) {
                var newPath = filePath.replace('/frontend/src', '');
                console.log('inject script = '+ newPath);
                return '<script src="/static/' + newPath  + '"></script>';
            }

执行后,我在控制台中什么都没有(除了标准的 gulp 输出),并且未转换的文件路径出现在结果文件中。看起来我的自定义转换没有运行,而是使用默认转换。

4

2 回答 2

6

/**/*.js即使有多个级别(而不是) ,以下内容也对我有用/*.js

gulp.task('inject', function() {
    gulp.src('./test.html')
        .pipe(inject(
            gulp.src(['./Content/js/*.js'], {read: false }),
            {
                transform: function (filePath, file, i, length) {
                    var newPath = filePath.replace('/Content/js/', '');
                    console.log('inject script = '+ newPath);
                    return '<script src="/static/' + newPath  + '"></script>';
                }
            })
        )
        .pipe(gulp.dest('./'));
});
于 2016-01-03T20:47:06.813 回答
1

gulp-inject插件的转换功能按预期工作。gulp任务的配置如下——

gulp.src(path.normalize('./app/index.html'))
    .pipe(inject(
        gulp.src([path.normalize('./frontend/src/*.js')], {read: false}), {
            transform : function ( filePath, file, i, length ) {
               var newPath = filePath.replace(path.normalize('/frontend/src'), '');
               console.log('inject script = '+ newPath);
               return '<script src="/static' + newPath  + '"></script>';
            }
        }
    ))
    .pipe(gulp.dest('./build'));

为了确保它可以跨平台(Windows、Linux)工作,path.normalize使用

检查示例代码 - https://github.com/pra85/gulp-inject-example

于 2016-01-07T18:30:11.150 回答