如何使用Webpack呈现.ejs文件?

时间:2019-01-28 18:13:33

标签: node.js webpack ejs

我在尝试将 .ejs 文件与Webpack一起使用时遇到问题。我尝试了很多软件包,但还没有弄清楚。我有五个要渲染的文件,并且有一个 layout.ejs 作为我的应用程序的基础。我正在使用 ejs-loader ,因为它是最受欢迎的。当我运行 webpack 时,出现以下错误:

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

我对模块捆绑比较陌生,并尝试尽可能接近文档。

webpack.config.js

const path = require('path')
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const nodeExternals = require('webpack-node-externals')

const config = {
  target: 'node',
  mode: 'development',
  entry: './app.js',
  externals: [nodeExternals()],
  output: {
    path: path.join(__dirname, './dist'),
    filename: 'bundle.js'
  },
  module: {
    rules: [{
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader'
      },
      {
        test: /\.ejs$/,
        loader: 'ejs-loader?variable=data'
      },
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './views/layout.ejs',
      hash: true,
    }),
    new webpack.ProvidePlugin({
      _: "underscore"
    })
  ]
}

module.exports = config;

layout.ejs

<!DOCTYPE html>
<html lang="en">

<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" />
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/"
    crossorigin="anonymous">
  <link rel="stylesheet" href="https://bootswatch.com/4/flatly/bootstrap.min.css" />
  <title>MyApp</title>
</head>

<body>
  <div class="container">
    <%- body %>
  </div>

  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
    crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut"
    crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k"
    crossorigin="anonymous"></script>
  <script src="../dist/bundle.js"></script>
</body>

</html>

0 个答案:

没有答案