简体   繁体   English

在与gulp捆绑后内联JS ind EJS文件

[英]Inlining JS ind EJS file after bundling with gulp

I am trying to get the output of a gulp-browserify combo as inline JS in a EJS template. 我试图在EJS模板中获取gulp-browserify组合的输出作为内联JS。 The output needs to be a html file with inline JavaScript for reasons beyond my control. 由于我无法控制的原因,输出需要是带有内联JavaScript的html文件。 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. 我知道browserify返回一个流,所以我尝试使用'data'事件,但是我无法使用js文件中的实际代码填充脚本标记。

Index.ejs Index.ejs

<html>
<script><%= cscript %></script>
</html>

Index.js Index.js

console.log('this is a test');

Gulpfile 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. 答案在于节点流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. 要实现此目的,您需要在data事件期间连接块,并在流的end事件期间调用ejs方法。

Gulpfile: 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. Index.ejs也需要稍微调整以保持JS字符串在输出中不转义。

<html>
<script><%- cscript %></script>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM