Injects any source into any file.
gulp-source-injector
transforms content of each source file to a string and injects each transformed string into placeholders in the target stream files.
This plugin does not do any minification to source files, so whitespaces will be preserved. It's better to use it after transformations like gulp-terser
or gulp-clean-css
.
npm install --save-dev gulp-source-injector
Injection placeholders are comments as html syntax <!-- inject: filePath -->
and css/js syntax /* inject: filePath */
By default the injected file path is relative to each target file's cwd
. If the provided path starts with /
, it will be considered relative to the directory of gulpfile.js
Project structure
├── src
│ ├── css
│ │ └── style.css
│ ├── js
│ │ └── script.js
│ ├── template
│ │ └── head.html
│ └── index.html
└── gulpfile.js
Target file src/index.html
<html>
<head>
<!-- inject: /src/template/head.html -->
<style>
/* inject: ./css/style.css */
</style>
<script>
/*inject:js/script.js*/
</script>
</head>
<body>
<h1>Lorem Ipsum</h1>
</body>
</html>
gulpfile.js
const { task, src, dest } = require('gulp')
const inject = require('gulp-source-injector')
task('inject', () => {
return src('src/index.html')
.pipe(inject())
.pipe(dest('dist'))
})
or you can
import inject from 'gulp-source-injector'
and then
dist/index.html
after running gulp inject
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<meta title="test">
<style>
body {
background-color: #333;
}
h1 {
color: #EEE;
}
</style>
<script>
console.log('foobar')
</script>
</head>
<body>
<h1>Lorem Ipsum</h1>
</body>
</html>
Note that existing indentation won't be preserved.
Target file src/index.html
<html>
<head>
<style>
/* inject: ./css/style.css */
</style>
</head>
<body>
<h1>Lorem Ipsum</h1>
</body>
</html>
Source file src/css/style.css
body {
background-color: #333;
}
h1 {
color: #EEE;
}
dist/index.html
<html>
<head>
<style>
body {
background-color: #333;
}
h1 {
color: #EEE;
}
</style>
</head>
<body>
<h1>Lorem Ipsum</h1>
</body>
</html>