Solve woff file imports using Rollup

I am currently working on bundling a theme package using Rollup.js. The theme contains some global styles, specifically @font-face. I am importing the fonts and planning to inject them using styled-components injectGlobal.

However, I am encountering an issue when trying to bundle the package as Rollup is encountering errors with the font files. I initially thought that Webpack and Rollup could be used interchangeably, but it seems that is not the case. What is the correct approach to solve this problem?

Error message in console:

{ SyntaxError: /Users/****/sites/vz-react/packages/Theme/fonts/NeueHaasGroteskDisplayBold.woff: Unexpected character '' (1:4)
> 1 | wOFF: 6OS/2lZ`  VDMXwmtcmap@\(cvt `
    |     ^
  2 |
       fpgm
  3 | cgasp
               glyf
                    IrheadV66!vhheaV!$hmtxW;*+kernZ$;ĭloca'p\maxp+  [name+   y*/post4 prep57ڀڄxc`fb
  4 | 9X@ax3800fbf/py9#N3(!RxeTgf`uƌ3f`H(ݠw=wO?\ddGNf2,dod%tžl2;
...

globalStyles.js:

import NeueHassGroteskDisplayBold from '../fonts/NeueHaasGroteskDisplayBold.woff';
import NeueHassGroteskDisplay from '../fonts/NeueHaasGroteskDisplay.woff';
import NeueHassGroteskText from '../fonts/NeueHaasGroteskText.woff';
import NeueHassGroteskTextBold from '../fonts/NeueHaasGroteskTextBold.woff';

const injectGlobalStyles = () => `
  * {
    box-sizing: border-box;
  }

  *:focus {
    outline: #000 dotted 1px;
    outline-offset: 1px;
  }

  body {
    padding: 0;
    margin: 0;
  }

  @font-face {
    font-family: 'NHGDisplay';
    src: url(${NeueHassGroteskDisplayBold}) format("woff");
    font-weight: bold;
    font-style: normal;
  }

  @font-face {
    font-family: 'NHGDisplay';
    src: url(${NeueHassGroteskDisplay}) format("woff");
    font-weight: normal;
    font-style: normal;
  }

  @font-face {
    font-family: 'NHGText';
    src: url(${NeueHaasGroteskText}) format("woff");
    font-weight: normal;
    font-style: normal;
  }

  @font-face {
    font-family: 'NHGText';
    src: url(${NeueHaasGroteskTextBold}) format("woff");
    font-weight: bold;
    font-style: normal;
  }
`;

export default injectGlobalStyles;

Answer №1

Another technique involves encoding font files into base64 strings and grouping them together using the rollup-plugin-url plugin:

// rollup.config.js

import url from 'rollup-plugin-url'

export default {
  // ...
  plugins: [
    // ...
    url({
      // specify the font file types to include
      include: ['**/*.woff', '**/*.woff2'],
      // ensuring the files are always bundled with the code
      limit: Infinity,
    }),
  ],
  // ...
}

Then, proceed to import the fonts as you normally would:

// some-file.js

import { createGlobalStyle } from 'styled-components'
import MyFontWoff from '../fonts/my-font.woff'

const GlobalStyle = createGlobalStyle`
  @font-face {
    font-family: 'MyFont';
    src: url(${MyFontWoff}) format('woff');
    font-weight: normal;
    font-style: normal;
  }
`

Answer №2

My exhaustive search across Google yielded no solution on how to prevent Rollup from crashing while trying to pull in the font files.

The trick that worked for me was to move my imports to requires that are triggered when the export is executed.

Updated file:

const applyGlobalStyles = () => {

  const NeueHassGroteskDisplayBold = require('../fonts/NeueHaasGroteskDisplayBold.woff');
  const NeueHassGroteskDisplay = require('../fonts/NeueHaasGroteskDisplay.woff');
  const NeueHassGroteskText = require('../fonts/NeueHaasGroteskText.woff');
  const NeueHassGroteskTextBold = require('../fonts/NeueHaasGroteskTextBold.woff');

  return `
    * {
      box-sizing: border-box;
    }

    *:focus {
      outline: #000 dotted 1px;
      outline-offset: 1px;
    }

    body {
      padding: 0;
      margin: 0;
    }

    @font-face {
      font-family: 'NHGDisplay';
      src: url(${NeueHassGroteskDisplayBold}) format("woff");
      font-weight: bold;
      font-style: normal;
    }

    @font-face {
      font-family: 'NHGDisplay';
      src: url(${NeueHassGroteskDisplay}) format("woff");
      font-weight: normal;
      font-style: normal;
    }

    @font-face {
      font-family: 'NHGText';
      src: url(${NeueHassGroteskText}) format("woff");
      font-weight: normal;
      font-style: normal;
    }

    @font-face {
      font-family: 'NHGText';
      src: url(${NeueHassGroteskTextBold}) format("woff");
      font-weight: bold;
      font-style: normal;
    }
  `;
};

export default applyGlobalStyles;

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

The hierarchical structure in the DOM that mirrors an HTML table

While working on code to navigate the DOM for a table, I encountered an unexpected surprise. The DOM (specifically in FF) did not align with my initial expectations. Upon investigation, it appears that FF has automatically inserted a tbody along with sever ...

"Using Mxgraph's getPrettyXml function does not retrieve the value of a custom

I’m having trouble with mxgraph’s getPrettyXml() not capturing the value of Custom elements. In my customized template, it looks like this: <add as="symbol"> <Symbol label="Symbol" description="" href="" data="{[hi :bill]}"> &l ...

What is the best way to ensure consistency in the formatting of my email with that of my website?

A website has been created where users can fill out a form, and their data is saved into a JSON file. The displayed data on the site follows a specific format: However, when this data is sent via email, it ends up in a different format than intended: The ...

Is it possible for a node's promise chain to not execute synchronously?

Is it possible for functions to resolve out of sequence even with a sequence of promises/functions? I'm facing an issue where my view is not reflecting the correct results of a mongoose query despite having one function that performs a mongoose query ...

Dynamically insert the ng-if attribute into a directive

In my code, I have implemented a directive that adds an attribute to HTML elements: module1.directive('rhVisibleFor', function ($rootScope) { return{ priority: 10000, restrict: 'A', compi ...

Is it possible to expand the Angular Material Data Table Header Row to align with the width of the row content?

Issue with Angular Material Data Table Layout Link to relevant feature request on GitHub On this StackBlitz demo, the issue of rows bleeding through the header when scrolling to the right and the row lines not expanding past viewport width is evident. Ho ...

How to perfectly center the Bootstrap Modal using CSS styling

Looking for a way to vertically align the Bootstrap Modal? I've attempted using CSS with no success. I tried this: .modal-dialog { display: inline-block; text-align: left; vertical-align: middle; } However, the modal still displays in t ...

How can I convert JSON data from an array to an array of objects using JavaScript?

My goal is to load data into an ag-grid. I have obtained the json data in the following format: {"my_data":{"labels":[1,2,3,...], "idx":["idx1", "idx2", ...]}} In order to pass it to the grid, I need to transform it to this format: {"my_data":[{"labels" ...

AngularJS: The blend of bo-bind, bindonce, and the translate filter

I am currently working with angular 1.2.25, angular-translate 2.0.1, angular-translate-loader-static-files 2.0.0, and angular-bindonce 0.3.1. My goal is to translate a static key using bindonce. Here is the code snippet I have: <div bindonce> < ...

Spin the item around the axis of the universe

My goal is to rotate an object around the world axis. I came across this question on Stack Overflow: How to rotate a object on axis world three.js? However, the suggested solution using the function below did not resolve the issue: var rotWorldMatrix; / ...

What is the best way to center a CSS arrow vertically within a table cell?

I'm having trouble with aligning a CSS arrow next to some text inside a table cell... <td><div class="arrow-up"></div> + 1492.46</td> My goal is to have the arrow positioned to the left of the text and centered vertically wit ...

Issue: The GET request to a third-party API using Fetch API encountered a "TypeError: Failed to fetch" error

After conducting extensive research and investing hours into this issue, I am at the point where I need to seek assistance. I am attempting to make a GET call to a third-party Infutor API using the fetch API in my ReactJS Project. Initially, I encountered ...

What is the best way to align a button within a Jumbotron?

Struggling to find the right CSS placement for a button within a jumbotron. I attempted using classes like text-left or pull-left, but nothing seemed to work as I hoped. I believe a simple CSS solution exists, but it's eluding me at the moment. Ideall ...

Faulty Container - Excessive spacing issues

https://i.sstatic.net/Sp23W.png Currently enrolled in a Udemy course on Full Stack Development from scratch. The instructor often makes mistakes that require improvisation, like using <span> instead of <p> next to the sign-in. Additionally, ad ...

Adjust the Navbar to be Aligned Completely to the Left and Divide it into 12

I need my navbar to be split into 12 sections so that each item occupies one section, starting from the far left of the screen. The current alignment doesn't meet this requirement as shown in the image below; https://i.sstatic.net/irYqV.png Despite ...

Upgrading to SVG icons from font icons - Eliminate inline formatting

After making the decision to transition from font icons to SVG icons, I used Adobe Illustrator to create my SVGs and exported each individual icon using the following settings: Styling: Inline Style Font: SVG Images: Embed Object IDs: Layer Names Decimal ...

Result of utilizing Bootstrap Radio buttons

Looking at the HTML snippet below, I am trying to display two lines of radio buttons. However, when I click on a radio button in the first line and then proceed to click any radio button in the second line, the result of the radio button in the first line ...

Implementing event handlers with 'v-on' on dynamically inserted content using 'v-html' in Vue

Can Vue allow for the addition of v-on events on strings included in v-html? In this scenario, clicking the 'Maggie' link doesn't produce any action. It appears that it's not recognized by Vue. Is there an alternative method to achieve ...

What is the best way to dynamically insert an image into an <li> element?

I am looking to enhance my menu by adding an image below each li item as a separator. How can I achieve this using CSS? I want the images to automatically appear whenever a new li tag is added to the ul. Here is the HTML code: <ul class="menu"> ...

Is there a way to apply a setTimeout to a <div> element upon the first click, but not on subsequent clicks?

Check out the fiddle I've created: http://jsfiddle.net/dkarasinski/dj2nqy9c/1/ This is the basic code. I need assistance with a functionality where clicking on a black box opens a black background and then after 500ms a red box appears. I want the ...