Mat
Mat

Reputation: 101

Vue + webpack, convert font files to base64

I'm writing a library to import into other projects, to share custom components and styles. Problem is with font files, .woff/.ttf/etc.

//_fonts.scss
$woff_path: '~/woff';
$ttf_path: '~/ttf';

@font-face {
    font-family: "MyOpensans";
    src: url($woff_path + "opensans-regular-webfont.woff2") format("woff2");
    src: url($woff_path + "opensans-regular-webfont.woff") format("woff");
    src: url($woff_path + "OpenSans-Regular.ttf") format("font-type");
    font-style: normal;
...
}

$testfont: "MyOpensans", wingdings;

When I use $testfont in my scss, the url uses relative path, which of course doesn't work when imported into other projects. So, my thought was just use base64:

src: url(data:application/x-font-woff;charset=utf-8;base64;XXXX);

Works fine if I run the .woff files through a base64 convertor, and paste into _fonts.scss. But, I'd like webpack to do it for me. I've tried both base64-inline-loader and url-loader. Neither have worked. A bit more digging with url-loader. if I import "@/assets/woff/opensans-regular.webfont.woff2"; in my main.ts, I can see it does base64 it into a variable in the main source, but my _fonts.scss of course has no idea of this, and my _fonts.scss still has src as the relative path. It seems as though url-loader does nothing with url() inside scss.

Am I missing something? Is there a way I can get webpack to turn my url(file path) into url(data:xxx) for me? Or some other way to get custom fonts to work when compiled to a library?

Upvotes: 4

Views: 934

Answers (1)

DrMeers
DrMeers

Reputation: 4207

You might want to look into using something like base64-inline-loader

As per the example on that page:

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

Upvotes: 1

Related Questions