Webpack inline font with url-loader
Asked Answered
N

1

8

I’m trying to inline some fonts as base64-encoded Data URI’s but am having no luck with Webpack’s url-loader. Which is weird because the url-loader seems to be doing just that for my image and svg files. My setup is below:

directory structure

root/
|-src/
|--assets/
|
|----fonts/
|      icon-fonts/
|        fontawesome.woff2
|
|----styles/
|      fonts.css
|
|--components/
|   main.component.js
|...

webpack.config.js

module: {
  loaders: [
    {
      test: /\.(jpg|png|svg|woff2)$/,
      exclude: /node_modules/,
      loader: 'url?limit=100000&name=[name]-[sha512:hash:base64:7].[ext]'
    },
  ]
}

fonts.css

@font-face {
  font-family: FontAwesome;
  font-weight: normal;
  font-style: normal;
  src: url('../fonts/icon-fonts/fontawesome.woff2') format('woff2');
}

main.component.js

import fonts from '../assets/styles/fonts.css'
import React from 'react'

export class App extends React.Component {
  ...
}

output

output

Nero answered 15/1, 2017 at 2:4 Comment(0)
C
8

Not sure if url-loader is able to inline fonts, but my guess is not. You can use base64-inline-loader for this purpose.

NOTE:

Shown example didn't work for me because it exports files anyway.

{
   test: /\.(jpe?g|png|ttf|eot|svg|woff(2)?)(\?[a-z0-9=&.]+)?$/,
   use: 'base64-inline-loader?limit=1000&name=[name].[ext]'
}

however soon as I removed name from rule it works like a charm

{
  test: /\.(jpe?g|png|ttf|eot|svg|woff(2)?)(\?[a-z0-9=&.]+)?$/,
  use: 'base64-inline-loader'
}
Carlisle answered 27/11, 2017 at 15:43 Comment(1)
Note with the latest version of webpack and css-loader, we need to include the appropriate asset type within the rule like so: {test: /\.(css|woff(2)?)(\?[a-z0-9=&.]+)?$/,use: ['base64-inline-loader'], type: 'javascript/auto'}, see here for more details: webpack.js.org/guides/asset-modules/#general-asset-typeKunming

© 2022 - 2024 — McMap. All rights reserved.