【问题标题】:How to import HTML files in dist folder?如何在 dist 文件夹中导入 HTML 文件?
【发布时间】:2026-02-19 20:25:01
【问题描述】:

在我的开发环境中我给

res.sendFile(path.resolve(__dirname,'../Views/setpwd.html');

它在开发环境中运行良好。

但在生产中,即使我在 webpack 中添加了 html 加载器,视图也不会移动到 dist 文件夹。请问各位大神能帮帮我吗?

提前致谢

## Webpack 配置##

var path = require('path');
 var webpack=require('webpack');
 var nodeExternals = require('webpack-node-externals');
module.exports = {
     entry: './src/app.js',
     output: {
         path: path.resolve(__dirname,'dist'),
         filename: 'src/server.js',
     },
      target: 'node',
      externals: [nodeExternals()],
      module: {
         loaders: [{ test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader'}],
         loaders: [
            { test: /\.(html)$/, loader: "file" }
        ]
     },
     plugins: [
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false,
            },
            output: {
                comments: false,
            },
        }),
    ]
 }

deVdependencies

"devDependencies": {
    "babel-core": "^6.24.1",
    "babel-loader": "^7.0.0",
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-preset-env": "^1.5.1",
    "babel-preset-es2015": "^6.24.1",
    "file-loader": "^0.11.2",
    "webpack": "^2.6.1",
    "webpack-node-externals": "^1.6.0"
  },

【问题讨论】:

  • 您的配置似乎没有读取环境或在 dev 和 prod 之间做出任何区分
  • "dev": "nodemon --debug src/app.js --exec babel-node --presets es2015", "start": "node dist/src/server.js" 我是将 babel-cli 用于开发,所以我将 Webpack 用于生产

标签: html node.js express webpack


【解决方案1】:

如果我理解正确,您想使用 webpack 将 ../Views/*.html 中的 HTML 文件复制到 dist/ 目录。如果是这样,那么您需要使用copy-webpack-plugin

new CopyWebpackPlugin([
  {
    from: path.resolve(__dirname, '../path/to/views/directory'),
    to: path.resolve(__dirname, '../path/to/dist')
    ignore: ['.*']
  }
])

【讨论】:

  • 如果我的答案是正确的,那么请标记它。