You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

webpack-dev-server访问dist/style.css报404该如何调整配置?

问题原因

webpack-dev-server默认仅会将webpack构建生成的产物(比如你配置里的bundle.js)放到内存中提供访问,你通过node-sass手动生成到dist目录的style.css不属于webpack的构建产物,不会被加载到内存中,所以访问时返回404。

解决方法

在你的webpack.config.js中新增devServer配置项,指定dist目录为静态资源目录,让webpack-dev-server同时提供本地dist目录下所有文件的访问能力:

const path = require('path');
const MiniCssExtractPlugin = require("mini-css-extract-plugin")
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
  entry: "./src/index.ts",
  mode: "development",
  // 新增devServer配置
  devServer: {
    // webpack 5 写法
    static: {
      directory: path.join(__dirname, 'dist'),
    },
    compress: true,
    port: 8080,
    // 如果是webpack 4 写法替换上面的static为:
    // contentBase: path.resolve(__dirname, 'dist')
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: "ts-loader",
        exclude: /node_modules/,
      },
      {
        test: /\.css$/,
        use: [
          MiniCssExtractPlugin.loader, 
          'css-loader'
        ]
      },
    ],
  },
  resolve: {
    extensions: ['.tsx', '.ts', '.js'],
  },
  plugins: [
    new MiniCssExtractPlugin(
      { 
        filename: './style.css' 
      }),
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, "dist", "index.html"),
      inject: false
    })
  ],
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  },
};

修改配置后重启webpack-dev-server,就能正常访问style.css了。

可选优化

如果你不需要webpack处理CSS文件,完全用node-sass生成,可以删除配置中的MiniCssExtractPlugin相关引用和CSS处理规则,减少不必要的构建逻辑。

内容的提问来源于stack exchange,提问作者Ari Lacenski

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 08:15:00