我正在尝试使用Webpack使用Pug设置一个基本的Express应用程序。这是我的文件树:
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'
}
我遇到的问题是快递应用程序找不到index.pug文件。当我启动服务器并转到localhost:3000时,我收到一条错误消息:
Error: Failed to lookup view "index" in views directory "\views"
答案 0 :(得分:2)
path.join(__dirname + 'views')
正在查看服务器目录,因此将其替换为./views
或者在您的webpack配置中添加此选项
node: {
__dirname: true,
__filename: true,
},
检查服务器端here
的webpack文档