Home > Software engineering >  Webpack cannot find dist/style.css
Webpack cannot find dist/style.css

Time:10-16

Using webpack-dev-server, I'm able to load ./dist/index.html at the root path (0.0.0.0:8080) and to view ./dist/bundle.js at 0.0.0.0:8080/bundle.js. I'm getting a 404 when I try to load (0.0.0.0:8080/style.css).

The CSS in my ./dist directory is generated by an npm command running node-sass, not using webpack.

dist/
 - index.html
 - bundle.js
 - style.css

webpack.config.js


    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",
      module: {
        rules: [
          {
            test: /\.tsx?$/,
            use: "ts-loader",
            exclude: /node_modules/,
          },
          {
            test: /\.css$/,
            use: [
              MiniCssExtractPlugin.loader, // instead of style-loader
              'css-loader'
            ]
          },
        ],
      },
      resolve: {
        extensions: ['.tsx', '.ts', '.js'],
      },
      plugins: [
        new MiniCssExtractPlugin(
          { 
            filename: './style.css' 
            //also tried: path.resolve(__dirname, "dist", "style.css") 
          }),
        new HtmlWebpackPlugin({
          template: path.resolve(__dirname, "dist", "index.html"),
          inject: false
        })
      ],
      output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist')
      },
    };

(from https://blog.jakoblind.no/css-modules-webpack/)

What should I add or change so that my browser can reach the CSS file at ./dist/style.css?

CodePudding user response:

webpack-dev-server doesn't actually store files on disk, it just makes them on the fly and then holds them in memory to answer http requests. So by default, it won't know about anything in dist; it only knows how/where to serve files that it can also generate.

However, you can configure it to serve additional existing files from disk (and watch them for changes), by adding this to your webpack config. In Webpack 5:

devServer: {
  static: {
      directory: path.join(__dirname, 'dist')
  }
}

In Webpack 4 it was called contentBase:

devServer: {
  contentBase: path.join(__dirname, 'dist'),
  watchContentBase: true
}
  • Related