【问题标题】:Can't find index.html when bundling Node.js server with Webpack将 Node.js 服务器与 Webpack 捆绑时找不到 index.html
【发布时间】:2019-02-01 01:24:54
【问题描述】:

我正在尝试设置 webpack 来捆绑我的后端代码。

我的 webpack 配置如下:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const nodeExternals = require('webpack-node-externals');

const outputDirectory = 'dist';

const client = {
  mode: 'production',
  entry: {
    'app': [
      'babel-polyfill',
      './client/index.js'
    ]
  },
  output: {
    path: path.join(__dirname, outputDirectory),
    publicPath: '/',
    filename: 'bundle.js'
  },
  module: {
    rules: [
      { 
        test: /\.(js|jsx)$/, exclude: /node_modules/, loader: 'babel-loader'
      },
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader']
      },
      {
        test: /\.(gif|svg|jpg|png)$/,
        loader: "file-loader"
      }
    ]
  },
  plugins: [
    new CleanWebpackPlugin([outputDirectory]),
    new HtmlWebpackPlugin({
      template: './index.html',
    })
  ]
}

const server = {
  mode: 'production',
  target: 'node',
  entry: {
    'app': [
      './server/server.js'
    ]
  },
  externals: [nodeExternals()],
  output: {
    path: path.join(__dirname, '/server'),
    filename: 'server.bundle.js'
  }
}

module.exports = [client, server]

如果我运行非 webpack server.js,一切正常。但是,如果我运行 webpack 捆绑的 server.bundle.js,则会快速抛出:

Error: ENOENT: no such file or directory, stat '/dist/index.html'

两个服务器文件位于同一目录中。有没有人遇到过这个问题?

【问题讨论】:

  • 我可以看看你的客户端配置吗?
  • @AliDoustkani 添加了

标签: node.js express webpack


【解决方案1】:

我想通了,webpack 的文档中没有明确说明,但是你需要在使用 express 时配置一个“节点”属性

例如。将此添加到您的配置中

  node: {
    // Need this when working with express, otherwise the build fails
    __dirname: false,   // if you don't put this is, __dirname
    __filename: false,  // and __filename return blank or /
  },

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-07
    • 2020-03-04
    • 1970-01-01
    • 1970-01-01
    • 2013-04-19
    • 1970-01-01
    相关资源
    最近更新 更多