MiniCssExtractPlugin public path not working

梦想与她 提交于 2019-12-23 09:32:16

问题


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'
        ],

     }

Any help???


回答1:


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,

    }),
  ]
};


来源:https://stackoverflow.com/questions/51055490/minicssextractplugin-public-path-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!