MiniCssExtractPlugin public path not working
Asked Answered
R

1

17

I am using MiniCssExtractPlugin to lazyload CSS files in my React application.

I have given publicPath option for MiniCssExtractPlugin but it is not taking this option value, it is taking output.publicPath option.

config: {
  test: /\.(css)?$/,
  use: [{
    loader : MiniCssExtractPlugin.loader,
    options : {
      publicPath : '../'
    }},
    'css-loader'
    ],
}
Reside answered 27/6, 2018 at 5:58 Comment(0)
H
26

Seems as though your not the only one confused, 52 comments on how to get this right. The issue of publicPath in html-webpack-plugin was similar and helped. However, the biggest help was from npm run ejecting out of the create-react-app and inspecting the webpack.config.js files.

TL;DR: You need to specify the save path in the plugin constructor.

new MiniCssExtractPlugin({
  // Options similar to the same options in webpackOptions.output
  filename: "assets/css/[name].css",
}),

You might need to re-think the module output logic. Avoid specifying a nested path in module.output.path e.g. public/assets/js, instead set the root directory: public and set the nesting for the filename key: assets/js/[name].js.

You can then specify a publicPath in the main module.output that you would use for subdomains or CDN's etc.

The final complete config worked for me:

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

const publicPath = '/';

module.exports = {
  entry: './_src/_js/index.js',
  output: {
    filename: 'assets/js/[name].js',
    path: path.resolve(__dirname, 'dist'),
    publicPath: publicPath,
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
          },
          'css-loader',
        ],
      },
      {
        test: /\.(png|svg|jpg|gif)$/,
        use: [
          {
            loader: 'file-loader',
            options: {
              name: 'assets/images/[name].[ext]',
            },
          },
        ]
      },
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: ['babel-loader','eslint-loader']
      },
    ],
  },
  plugins: [
    new MiniCssExtractPlugin({
      // Options similar to the same options in webpackOptions.output
      // both options are optional
      filename: "assets/css/[name].css",
    }),
    new HtmlWebpackPlugin({
      inject: true,

    }),
  ]
};
Hives answered 4/7, 2018 at 7:1 Comment(1)
how do I change resource url relative to assets/css/ if directory structure changes.Hale

© 2022 - 2024 — McMap. All rights reserved.