Webpack “OTS parsing error” loading fonts

前端 未结 13 1241
[愿得一人]
[愿得一人] 2020-11-28 20:51

My webpack config specifies that fonts should be loaded using url-loader, and when I try to view the page using Chrome I get the following error:



        
13条回答
  •  盖世英雄少女心
    2020-11-28 21:14

    TL;DR Use absolute paths to your assets (including your complete hostname) by setting your output.publicPath to e.g. "http://example.com/assets/".

    The problem

    The problem is the way that URLs are resolved by Chrome when they're parsed from a dynamically loaded CSS blob.

    When you load the page, the browser loads your Webpack bundle entry JavaScript file, which (when you're using the style-loader) also contains a Base64 encoded copy of your CSS, which gets loaded into the page.

    This is what it looks like in Chrome DevTools

    That's fine for all the images or fonts which are encoded into the CSS as data URIs (i.e. the content of the file is embedded in the CSS), but for assets referenced by URL, the browser has to find and fetch the file.

    Now by default the file-loader (which url-loader delegates to for large files) will use relative URLs to reference assets - and that's the problem!

    These are the URLs generated by file-loader by default - relative URLs

    When you use relative URLs, Chrome will resolve them relative to the containing CSS file. Ordinarily that's fine, but in this case the containing file is at blob://... and any relative URLs are referenced the same way. The end result is that Chrome attempts to load them from the parent HTML file, and ends up trying to parse the HTML file as the content of the font, which obviously won't work.

    The Solution

    Force the file-loader to use absolute paths including the protocol ("http" or "https").

    Change your webpack config to include something equivalent to:

    {
      output: {
        publicPath: "http://localhost:8080/", // Development Server
        // publicPath: "http://example.com/", // Production Server
      }
    }
    

    Now the URLs that it generates will look like this:

    Absolute URLs!

    These URLs will be correctly parsed by Chrome and every other browser.

    Using extract-text-webpack-plugin

    It's worth noting that if you're extracting your CSS to a separate file, you won't have this problem because your CSS will be in a proper file and URLs will be correctly resolved.

提交回复
热议问题