node.jsnpmgulpnode-modulesgulp-inject

Injecting JS into HTML pages with matching filenames


I want to be able to inject a .js file into the HTML page with the same filename using gulp-inject (i.e., index.min.js is injected into index.html, data.min.js is injected into data.html). I have the minified files stored in build/js and the .html is in src/. I've tried this:

src('src/*.html')
    .pipe(inject(src('build/js/*.min.js'), {
        starttag: '<!-- inject:{{path}} -->',
        relative: true
    }))
    .pipe(dest('build/'));

await Promise.resolve('Javascript injected.');

Here's the terminal output when running it with gulp:

[23:17:24] Starting 'injectJS'...
[23:17:24] Finished 'injectJS' after 19 ms
[23:17:24] gulp-inject Nothing to inject into data.html.
[23:17:25] gulp-inject Nothing to inject into index.html.

index.html file with associated start and end tags:

<!-- inject:index.min.js -->
<!-- endinject -->

Can this be achieved using gulp-inject by itself, or will I need other packages?


Solution

  • I managed to get it working. The issue was that by using relative: true in the options, the file path included ../build/js/ in front of the actual file name, which was solved by using ignorePath: '../build/js' to remove the extra path info. In the end, the inject call looked like this:

    inject(src('build/js/*.min.js', { read: false }), {
        removeTags: true,
        starttag: '<!-- inject:{{path}} -->',
        relative: true,
        ignorePath: '../build/js',
        transform: (path) => {
            return '<script src="js/' + path + '"></script>';
        }
    })