This browser does not support automatic publicPath in Webpack5

While I was working on webpack 4.44.2, I encountered this error when transitioning to webpack 5.0.0

ERROR in ./src/assets/sass/styles.scss Module build failed (from ./node_modules/mini-css-extract-plugin/dist/loader.js): Error: Automatic publicPath is not supported in this browser at E:\maktab\Control-panel\newcontrol\final-control\node_modules\css-loader\dist\cjs.js!

The error stems from the font file path in fonts.scss

@font-face {
    font-family: "Janna LT";
    src: local("Janna LT"), url(../fonts/janna.woff) format("woff");
    font-weight: normal;
}

@font-face {
    font-family: "Janna LT";
    src: local("Janna LT"), url(../fonts/janna-bold.woff) format("woff");
    font-weight: bold;
}

My source structure https://i.sstatic.net/vKyfW.png

Distribution structure https://i.sstatic.net/mLgmF.png

webpack.config.js

const path = require('path');

const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { CleanWebpackPlugin } = require('clean-webpack-plugin');

module.exports = {
    entry:  {
      'main': './src/index.js',
    },
  
    output: {
      path: path.join(__dirname, "/dist"),
      filename: '[name].js',
    }, 

    devServer: {
        contentBase: path.join(__dirname, "/dist"),
        port: 8087,
        writeToDisk: true,
        overlay :true
    },
    

    module: {
        rules: [
    
            {
                test: /\.html$/,
                use: [
                    {
                        loader: "html-loader",
                    }
                ]
            },

            {
                test: /\.(sa|sc|c)ss$/,
                use: [
                MiniCssExtractPlugin.loader, 
                'css-loader', 
                'postcss-loader',
                'sass-loader'
                ]
            },
                    
            {
                test: /\.(png|svg|jpe?g|gif)$/,
                exclude: /fonts/,
                use: [
                    {
                        loader: "file-loader", 
                        options: {
                        name: '[name].[ext]',
                        outputPath: "/assets/images",
                        }
                    }
                ]
            },

            {
                test: /\.(svg|eot|woff|woff2|ttf)$/,
                exclude: /images/,
                use: [
                    {
                        loader: "file-loader", 
                        options: {
                        name: '[name].[ext]',
                        outputPath: "assets/fonts",
                        }
                    }
                ]
            },

        ]
    },

    plugins: [
        new CleanWebpackPlugin(),

        new HtmlWebpackPlugin({ 
          filename: "index.html",
          template: "./src/index.html",
          chunks: ['main']
        }),
      

        new MiniCssExtractPlugin({filename: "assets/css/styles.css"}),
        new OptimizeCSSAssetsPlugin({}),
    ]
    
} 

styles.scss

@import "base/fonts";
@import "base/global";
@import "base/typography";
@import "base/links";
@import "components/components";
@import "components/demo";

index.js

import './assets/sass/styles.scss';
import 'normalize.css/normalize.css';

console.log("helloworld from webpack5");

Answer №1

None of the recommended fixes resolved my issue. What ultimately made a difference was when I specifically set publicPath to an empty value.

output: {
  publicPath: '',
  ...
}

Answer №2

I came across a similar issue where my code was compiling into the dist-folder without any additional structure. To resolve this, I found a simple solution that worked for me as I only needed an empty path.

'module': {
        rules: [
            {
                test: /\.css$/,
                use: [
                    {
                        loader: MiniCssExtractPlugin.loader, 
                        options: {
                            publicPath: ''
                        }
                    },
                    {
                        loader: "css-loader"
                    }
                ]
            }
        ]
    }

If you want to get creative, you can also try something like this:

{
    loader: MiniCssExtractPlugin.loader,
    options: {
        publicPath: (resourcePath, context) => {
            return path.relative(path.dirname(resourcePath), context) + '/';
        },
    },
},

For more information, check out the details here: https://webpack.js.org/plugins/mini-css-extract-plugin/#the-publicpath-option-as-function

Answer №3

An issue has been identified with mini-css-extract-plugin versions 1.3.8 and below when used with Webpack 5. The error occurs when a stylesheet makes reference to a resource using url(...) without the publicPath option being explicitly set in the Webpack configuration.

I have taken the initiative to replicate and report this problem on GitHub: https://github.com/webpack-contrib/mini-css-extract-plugin/issues/707

Luckily, version 1.3.9 was released yesterday and it addresses this issue. Simply upgrade to resolve the error.

Answer №4

If you're looking for a solution, consider the following approach:

// Include output.publicpath
output: {
  publicPath: '/',
  ...
}

Answer №5

To configure your webpack.config.js, you can either use environment variables or specify the root path.

//step-1 const ASSET_PATH = process.env.ASSET_PATH || '/';

//step-2 Include the following inside the output object: publicPath: ASSET_PATH

//step-3 Include the following inside the plugins: 'process.env.ASSET_PATH': JSON.stringify(ASSET_PATH)

For more detailed information, check out the link below: https://webpack.js.org/guides/public-path/

Answer №6

One valuable tip is to incorporate the publicPath parameter into the options section of the MiniCssExtractPlugin.loader when configuring webpack.

To learn more, check out: mini-css-extract-plugin

  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
            options: {
              publicPath: '/public/path/to/',
            },
          },
          'css-loader',
        ],
      },
    ],
  },

Answer №7

I encountered a similar issue when trying to load images using the 'file-loader' in my project. Initially, I only specified the outputPath for the images. However, after adding the publicPath with the same value, the problem was resolved.

{
    test: /\.png$/i,
    use: {
        loader: 'file-loader',
        options: {
            name: "[name].[ext]",
            outputPath: "images",
            publicPath: 'images',
        }
    }
}

The outputPath parameter is used to determine the directory where the images should be placed.

On the other hand, the publicPath parameter specifies the path that will be inserted into the src attribute of the img element in HTML.

<img src="images/example.png"/>

It is important that both outputPath and publicPath have the same value for proper functionality.

Answer №8

Make sure to pay close attention to the <script> tag within your index.html file. The default type for this tag should not be set to module.

Correct:

<script src="./build/bundle.js"></script> 

Error:

<script type="module" src="./build/bundle.js"></script>

Answer №9

For the React application I am distributing on third-party websites, I have opted to include a script tag only instead of generating a separate CSS file using style-loader.

To resolve the problem at hand, I successfully addressed it by specifying an output.publicPath in the webpack configuration for production and updated to the most recent version of webpack.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I use React.JS to scroll horizontally to a specific div id?

scrollCustom() { document.getElementById("myID").scrollIntoView({"block":"center"}) } My attempt at using scrollIntoView({"block":"center"}) was flawless in Chrome, but encountered problems in Internet Explorer! ...

Tips for transferring information to a textarea within a bootstrap modal by selecting a cell in a table

I need to enable users to edit information in a table. One cell in the table contains text. Here is an excerpt from the table: <table class="table table-striped table-hover" id="table_id"> <thead> <tr> <th>Event</th& ...

Techniques for verifying phone numbers from various countries

The number of digits in a mobile number differs from country to country. I have tried using regular expressions, however, for example, India allows 10 digits, but this does not validate UAE, where the number of digits can range from 7 to 9. ...

Unable to use saved images with jQuery Slider

I'm currently facing an issue with adding a jQuery slider to my website. It seems that the slider is not displaying images that are saved on my computer, only images from external websites. Below is the code snippet where I have included an image fil ...

What are the reasons for not accessing elements in a more "direct" way like elemId.innerHTML?

Recently, I came across a piece of JavaScript code that accesses HTML elements using the shorthand elementID.innerHTML. Surprisingly, it worked perfectly fine, but interestingly, most tutorials opt for the traditional method of using document.getElementByI ...

Discover the method for populating Select2 dropdown with AJAX-loaded results

I have a basic select2 box that displays a dropdown menu. Now, I am looking for the most effective method to refresh the dropdown menu every time the select menu is opened by using the results of an AJAX call. The ajax call will yield: <option value=1 ...

Guide on implementing a progress bar for file uploads with JavaScript and AJAX request

I am looking to implement a progress bar in my file uploader. Below is the ajax call I have set up for both file upload and progress tracking. $(function() { $('button[type=button]').click(function(e) { e.preventDefault(); ...

What is the best way to title an uploaded chunk with HTML5?

Here is the script I am working with: function upload_by_chunks() { var chunk_size = 1048576; // 1MB function slice(start, end) { if (file.slice) { return file.slice(start, end); } else if (file.webkitSlice) { ...

When attempting to compress JavaScript with uglify-js, an unexpected token error occurs with the symbol ($)

When attempting to compress Bootstrap 4 js file using uglify-js, I encountered an error. The error message reads as follows: "Parse error at src\bootstrap\alert.js:1,7 import $ from 'jquery' ERROR: Unexpected token: name ($)". Now I am ...

Implementing an Angular theme in a project using Node.js, MySQL, and Express

I'm a beginner with node, angular, and express. I've managed to create a REST API using node+express+mysql, but now I need help integrating the blur-admin theme into my existing project. Despite getting the theme to run separately with gulp, I&ap ...

Accessing the value of a field using JavaScript/jQuery

Welcome to my page! I am working on obtaining the current Start and Finish date values. I plan to add a button for users to click, which will then retrieve all dates and display them somewhere on the page. But for now, I just need a way to access the date ...

Ways to quickly terminate a pipeline in a JavaScript transformation

Issue: I am facing a challenge with handling large files (>10GB). At times, I need to process the entire file while other times I only need to sample a few lines. The processing mechanism involves a pipeline: pipeline( inStream, ...

What could be the reason behind the occurrence of an error after deleting certain lines of code

The code below is functioning correctly. obj = { go: function() { alert(this) } } obj.go(); // object (obj.go)(); // object (a = obj.go)(); // window (0 || obj.go)(); // window However, an error arises when I comment out the first two lines. obj ...

How can I trigger an audio element to play using onKeyPress and onClick in ReactJS?

While attempting to construct the Drum Machine project for freeCodeCamp, I encountered a perplexing issue involving the audio element. Despite my code being error-free, the audio fails to play when I click on the div with the class "drum-pad." Even though ...

The URL is not being updated despite changes in document.location hash

I have created a script that toggles (show/hide) between different DIVs on the page (highlighted below in the various boxes =). However, I am facing an issue with updating the URL string when switching between different DIVs. For instance, if I navigate t ...

Using async/await keywords in React Native while iterating through an array and calling an API does not result in successful resolution

When attempting to request data from my API in this manner: export default ({ navigation }) => { // Call getMovieImages with the id of the likedMovies from the state.likedMovies const { getMovieImages, state:{ likedMovies }} = useContext(MovieContext); ...

AngularJS: Struggling to display modal window with minified AngularJS code

I have successfully created a model dialog using the following JavaScript code, but when I minify the script, I encounter an error preventing the model dialog from opening. The error message states: Error: [$injector:unpr] Unknown provider: aProvi ...

Tips for estimating a value within a dataset using JavaScript

The Main Idea My inquiry revolves around the concept of predicting values from a dataset using JavaScript. To better illustrate my issue, I will provide an example of the desired outcome. If you are familiar with Mathematica, you may be aware of the Pred ...

Disappearance of attribute in asp .net TextBox

Here is my asp .net code snippet: <asp:TextBox CssClass="siteinput required" ID="TextTitle" runat="server" Width="100%" MaxLength='<%# int.Parse(Request.QueryString["id"]) == 49 ? 40 : 15 %>' placeholder="Title" required="required">& ...

Stop iFrame from inheriting parent CSS styles

Is there a way to prevent an iFrame object from inheriting CSS properties from the main page? Specifically: I have created an iFrame object in my main class, and I want to adjust the opacity of the main page without affecting the iFrame. However, when I ...