2017-04-11 84 views
1

我想動態地插入bundle.js而不執行EJS模板,但我得到下面的錯誤。有沒有辦法只插入JS而不執行EJS模板?html-webpack-plugin - 如何插入webpack bundle.js而不執行EJS模板

ERROR in Template execution failed: ReferenceError: description is not defined 

ERROR in ReferenceError: description is not defined 

我使用節點實際渲染的模板,我只是想包文件可以動態地插入在template.ejs

res.status(200).render('template', 
{          
description: description, 
title:title 
}); 

的WebPack配置:

output: { 
     path: path.join(__dirname, 'dist'), 
     filename: "output.[hash].bundle.js", 
     publicPath: '/' 
    }, 
    new HtmlWebpackPlugin({ 
       inject: 'body', 
       template: 'views/template.ejs' 
      }), 

模板。 ejs

<!DOCTYPE html> 
<html lang="en" class="ddhub-site"> 
<head> 
    <meta charset="utf-8"> 
    <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
    <meta http-equiv="X-UA-Compatible" content="IE=edge"> 
    <meta name="format-detection" content="telephone=no"> 
    <meta description=<%=description%>/> 
    <title> <%= title %> </title> 
</head> 
<body></body> 
</html> 

回答

0

我最終使用了一個簡單的自定義插件,其中包含一個關於github問題的信息。

var fs = require("fs"); 
const path = require('path') 

function UpdateBundleJsPlugin(options) { 
    // Setup the plugin instance with options... 
} 

UpdateBundleJsPlugin.prototype.apply = function(compiler) { 
    compiler.plugin("done", function(statsData) { 
     const stats = statsData.toJson(); 

     if (!stats.errors.length) { 
      const htmlFileName = "search.ejs"; 
      const html = fs.readFileSync(path.join('./views',htmlFileName), "utf8"); 

      // need to read the final js bundle file to replace in the distributed index.html file 
      const asset = stats.assets[0]; 
      let htmlOutput = html.replace(/static\/.*bundle\.js/, 'static/'+asset.name); 

      fs.writeFileSync(
       path.join('./views', htmlFileName), 
       htmlOutput); 
     } 
    }); 
}; 

module.exports = UpdateBundleJsPlugin;