ShocKwav3_
ShocKwav3_

Reputation: 1760

how to render a .ejs file and view it after bundling with webpack in node js?

This is my webpack config:

{
    entry: './app.js',
    output: {
      path: path.resolve(__dirname, 'dist'),
      filename: "bundle.js"
    },
    module: {
      rules: [
        {
          test: /\.js$/,
          exclude: /(node_modules)/,
          use: {
            loader: 'babel-loader',
            options: {
              presets: ['env', 'es2015', 'stage-2']
            }
          }
        }
      ]
    },
    plugins: [
      new HtmlWebpackPlugin({
        template: './views/index.ejs',
        hash: true,
      })
    ],
    node: {
        __dirname: false
    },
    target: 'node'
});

This is my server code

    const express = require('express');
    const app = express();
    const path = require('path');
    const port = process.env.PORT || 3000;
    app.use(express.static(path.join(__dirname, '..', 'public')));

    app.set('views', path.join(__dirname, '..', 'views'));

    app.set('view engine', 'ejs');

    app.get('/', (req, res) => {
      res.render('index');
    });

    app.listen(port, ()=>{
      console.log(`Live on ${port}`);
    });

when i build it with webpack and run it gives me error. I dont see the index.ejs working. I have tried a lot of things. Nothing is working.

Is it possible to run the output file and it starts the index.ejs? for html files it works. Help would be much appreciated!

Upvotes: 0

Views: 2300

Answers (1)

Gonras Karols
Gonras Karols

Reputation: 1190

Add this line after you set your view engine, this should do the trick..

app.set("view engine", "ejs");   
app.engine('.ejs', ejs);  // <-- this one

Apparently, it's a result of a bug in webpack and an issue was already opened.

Upvotes: 2

Related Questions