I am trying to get the output of a gulp-browserify combo as inline JS in a EJS template. The output needs to be a html file with inline JavaScript for reasons beyond my control. I know browserify returns a stream so I tried playing around with the 'data' event but I cannot get the script tag filled with the actual code from the js file.
Index.ejs
<html>
<script><%= cscript %></script>
</html>
Index.js
console.log('this is a test');
Gulpfile
const ejs = require('gulp-ejs');
gulp.task('build:creative', () => {
const js = browserify({
entries: './src/creatives/index.js'
}).transform('babelify').bundle()
.on('data', (file) => {
const jsText = file.toString();
gulp.src('./src/creatives/index.ejs')
.pipe(ejs({
cscript: jsText
}))
.pipe(gulp.dest('dist/creatives'));
});
});
Expected output:
<html>
<script>console.log('this is a test');</script>
</html>
Actual output: Total Gibberish.
Does anybody have experience with this?
So, I was able to figure it out. The answer lay in the node stream API. To achieve this, you need to concat the chunks during the data
event and call the ejs method during the end
event of the stream.
Gulpfile:
gulp.task('build:creative', () => {
let jsString = '';
browserify({
entries: './src/creatives/index.js'
})
.transform('babelify')
.bundle()
.on('data', (file) => {
jsString += file.toString();
})
.on('end', () => {
gulp.src('./src/creatives/index.ejs')
.pipe(ejs({
cscript: jsString
}))
.pipe(gulp.dest('dist/creatives'));
});
});
Index.ejs needed a slight adjustment as well to keep the JS string unescaped in the output.
<html>
<script><%- cscript %></script>
</html>