将Pug与NodeJS和Webpack一起使用

臭狗编码

我正在尝试使用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'
}

我遇到的问题是Express应用程序找不到index.pug文件。当我启动服务器并转到localhost:3000时,我收到一条错误消息:

Error: Failed to lookup view "index" in views directory "\views"
戴维·比利亚雷亚尔

path.join(__dirname + 'views')正在查找服务器目录内部,因此将其替换为./views或在您的webpack配置中添加此选项

node: {
    __dirname: true,
    __filename: true,
},

在此处查看Webpack文档以获取服务器端信息

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章