Gulp-inject transform doesn't work

南楼画角 提交于 2019-12-08 17:28:19

问题


I've tried to setup gulp-inject to inject dependencies into index.html. Everything works fine except transform function. I need to replace part of filepath in the following way: /frontend/src/ --> /static/ I've tried to do it like this (copy-pasted from somewhere):

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

After executing, I have nothing (except standard gulp output) in the console, and un-transformed filepath appears in result file. Looks like my custom transform just doesn't run, and the default transform works instead.


回答1:


The following is working for me even with multiple levels (/**/*.js instead of /*.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('./'));
});



回答2:


gulp-inject plugin's transform function works as intended. The configuration of the gulp task is as follows -

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'));

To make sure it works cross-platform (Windows,Linux), path.normalize is used

Check the example code at - https://github.com/pra85/gulp-inject-example



来源:https://stackoverflow.com/questions/34482276/gulp-inject-transform-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!