I am trying to set up a basic Express application with Pug using Webpack. This is my file tree:
build
|-views
|-index.pug
|-app.js
|-app.js.map
server
|-app.js
package.json
webpack.config.js
app.js:
const express = require('express');
const app = express();
const path = require('path');
app.set('port', process.env.PORT || 3000);
app.set('view engine','pug');
app.set('views', path.join(__dirname + 'views'));
app.get('/',(req,res) => {
res.render('index');
});
var server = app.listen(app.get('port'), () => {
console.log('Express server is listening on port ' + server.address().port);
});
webpack.config.js:
const webpack = require('webpack');
const path = require('path');
const fs = require('fs');
let nodeModules = {};
fs.readdirSync('node_modules')
.filter((x) => {
return ['.bin'].indexOf(x) === -1;
})
.forEach((mod) => {
nodeModules[mod] = 'commonjs ' + mod;
});
module.exports = {
entry: './server/app.js',
target: 'node',
output: {
path: path.join(__dirname, 'build'),
filename: 'app.js'
},
externals: nodeModules,
plugins: [
new webpack.IgnorePlugin(/\.(css|less)$/),
new webpack.BannerPlugin({banner: 'require("source-map-support").install();', raw: true, entryOnly: false })
],
devtool: 'sourcemap'
}
The problem that I am having is that the express app can't find the index.pug file. When I start the server and go to localhost:3000 I get an error message:
Error: Failed to lookup view "index" in views directory "\views"
path.join(__dirname + 'views')
is looking inside the server directory so replace it with ./views
Or in ur webpack config add this option
node: {
__dirname: true,
__filename: true,
},
Check the webpack documentation for server side here