【问题标题】:Webpack Dev Server - Not displaying index.htmlWebpack 开发服务器 - 不显示 index.html
【发布时间】:2021-12-15 09:50:13
【问题描述】:

当我转到 localhost:5000 时,我的 index.html 文件没有加载。 Webpack Dev Server 有没有办法获取我的根 index.html?解决此问题的最佳方法是什么。

文件夹结构:

├── dist
│   └── main.js
├── src
│   └── app
│       └── app.js
├── index.html
├── package-lock.json
├── package.json
└── webpack.config.js

webpack.dev.js:

const path = require('path');

module.exports = {
  mode: 'development',
  entry: './src/app/app.js',
  output: {
    filename: 'main.js',
    path: path.resolve(__dirname + 'dist'),
  },
  devServer: {
    static: {
      directory: path.join(__dirname, 'dist'),
    },
    port: 5000,
    open: true,
  },
};

【问题讨论】:

    标签: webpack webpack-dev-server


    【解决方案1】:

    最终使用 HtmlWebpackPlugin 并按照 Webpack HTML documentation 进行设置。所以现在我的文件结构和 webpack.dev.js 文件如下所示。我将index.html 移动到src 文件夹中。 HTMLWebpackplugin 会自动生成 index.html 文件中的所有 <script> 包含,并会在 dist 文件夹中创建一个 index.html 文件。

    文件夹结构:

    ├── dist
    │   └── // main.js and index.html will automatically be generated here
    ├── src
    │   ├── app
    │   │   └── app.js
    │   └── index.html // index now in src folder
    ├── package-lock.json
    ├── package.json
    └── webpack.config.js
    

    webpack.dev.js:

    const path = require('path');
    const HtmlWebpackPlugin = require('html-webpack-plugin'); // Add this
    
    module.exports = {
      mode: 'development',
      entry: './src/app/app.js',
      output: {
        filename: 'main.js',
        path: path.resolve(__dirname + 'dist'),
      },
      plugins: [
        new HtmlWebpackPlugin({
          template: './src/index.html',
        }),
      ],
      devServer: {
        static: {
          directory: path.join(__dirname, 'dist'),
        },
        port: 5000,
        open: true,
      },
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-09
      • 2017-01-09
      • 2018-12-02
      • 2020-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-03
      相关资源
      最近更新 更多