【问题标题】:Inlining JS ind EJS file after bundling with gulp与 gulp 捆绑后内联 JS ind EJS 文件
【发布时间】:2017-11-28 16:24:10
【问题描述】:

我正在尝试将 gulp-browserify 组合的输出作为 EJS 模板中的内联 JS。由于我无法控制的原因,输出需要是带有内联 JavaScript 的 html 文件。 我知道 browserify 返回一个流,所以我尝试使用“数据”事件,但我无法从 js 文件中获取填充实际代码的脚本标记。

索引.ejs

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

索引.js

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

Gulp 文件

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

预期输出:

<html>
    <script>console.log('this is a test');</script>
</html>

实际输出:Total Gibberish。

有人有这方面的经验吗?

【问题讨论】:

    标签: javascript gulp browserify ejs


    【解决方案1】:

    所以,我能够弄清楚。答案在于节点流 API。为此,您需要在data 事件期间连接块,并在流的end 事件期间调用ejs 方法。

    Gulp 文件:

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

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

    【讨论】:

      猜你喜欢
      • 2011-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-03
      • 1970-01-01
      相关资源
      最近更新 更多