2

我正在尝试使用 Webpack 使用 Pug 设置一个基本的 Express 应用程序。这是我的文件树:

build
  |-views
    |-index.pug
  |-app.js
  |-app.js.map
server
  |-app.js
package.json
webpack.config.js

应用程序.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"
4

1 回答 1

4

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

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

在此处查看服务器端的 webpack 文档

于 2017-07-28T18:11:29.490 回答