webpack5 devServer浏览器打开显示 can not get

发布时间 2023-08-03 18:10:56作者: 蓓蕾心晴

webpack5中通过使用 webpack-dev-server 插件,配置 devServer 来浏览器启动页面,对于单页面,我们可以直接配置打开首页,多页面,可以配置打开一个文件目录,选择各个页面的目录

当我们配置好 webpack 后,执行 npm run dev,浏览器打开经常会看到显示  can not get,即无法匹配服务器匹配的目录

这时我们在 devServer 下配置 static 为html源文件路径即可。

const path = require('path')
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { CleanWebpackPlugin } = require('clean-webpack-plugin')

module.exports = {
    entry: "./src/index.ts",
    output: {
        filename: 'main.js',
        path: path.resolve(__dirname, 'dist'),
        publicPath: '/',
    },
    devtool: "cheap-source-map",
    mode: 'development',
    resolve: {
        extensions: [".js", ".ts", ".tsx"],
    },
    devServer: {
        static: path.resolve(__dirname, './src/'),
        compress: true,
        host: '0.0.0.0',
        port: '9000',
        open: true,
        hot: true,
    },
    module: {
        rules: [
            {
                test: /\.ts$/i,
                use: {
                    loader: "ts-loader",
                },
                exclude: [/node_modules/],
            },
        ],
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: "./src/index.html",
            filename: "public.html",
        }),
        new CleanWebpackPlugin()
    ],
};

官方文档

注意以上配置,我使用的各个包版本如下:

{
  "name": "typescript",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "webpack serve",
    "build": "webpack"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "clean-webpack-plugin": "^4.0.0",
    "html-webpack-plugin": "^5.5.3",
    "ts-loader": "^9.4.4",
    "typescript": "^5.1.6",
    "webpack": "^5.88.2",
    "webpack-cli": "^5.1.4",
    "webpack-dev-server": "^4.15.1"
  }
}

而在我使用的稍微低一点的 webpack 版本中,devServer 配置浏览器打开目录是通过 contentBase 配置的,还不支持 static,最新版本中使用 contentBase 会报错没有该属性

老版本:

"webpack": "^5.75.0",
"webpack-bundle-analyzer": "^4.4.2",
"webpack-cli": "^4.6.0",
"webpack-dev-server": "^3.11.2",
 devServer: {
            contentBase: path.join(__dirname, './src/views'),
            inline: true,
            compress: true,
            host: '0.0.0.0',
            port: '9999',
            overlay: true,
            open: true,
            hot: true,
            watchOptions: {
                poll: true
            }
},

最新版本中 devServe 的 inline、overlay、watchOptions、contentBase 均已废弃。