Search code examples
webpackgatsby

Load a file as a string in Gatbsy


In Gatsby's SSR file I am doing this

const HeadComponents = [
  <script
    key={SESSION_SCRIPT_KEY}
    dangerouslySetInnerHTML={{
      __html: `(${sessionInit})()`,
    }}
  />,
];

export const onRenderBody = ({ setHeadComponents }, pluginOptions) => {
  setHeadComponents(HeadComponents);
};

export const onPreRenderHTML = ({
  getHeadComponents,
  replaceHeadComponents,
}) => {
  const headComponents = getHeadComponents();

  // reorder your array with the sort method, by putting session maker/fetch at top
  const orderedComponents = headComponents.sort(item =>
    item.key === SESSION_SCRIPT_KEY ? -1 : 1,
  );

  replaceHeadComponents(orderedComponents);
};

What am I trying to accomplish

Using Gatsby SSR I want to basically import a module and then have that bit of code live inside an inline script tag at the head of the index page

Background

sessionInit as of now, is just a function that I have defined locally (ya really don't need to know its guts), I load up its string representation because its in the same scope (see above).

However I want to externally import a component import X from 'utils' and have it also work inline, so I can be DRY.

I need the function to be a string, that is post processed, ie, import typescript file but get the final post-webpack code.

The reason I need to do this is because I am injecting some code that is supposed to come before the entire Gatsby framework is loaded. The code is fairly critical and needs to run ASAP

Things I have tried

I have tried using raw-loader and asset modules but to no avail, as the result I get is not the string itself but rather some kind of macro (?). I also found this guide but it did not help.

Any insight into this is appreciated.


Solution

  • So the fix for this is a bit..inelegant. Instead of trying to get webpack to work and load up sessionInit using import, I ended up resorting to importing the javascript file using fs

    __html: fs.readFileSync('./static/sessionInit.js').toString(),
    

    I lose the benefits of all the fun stuff webpack does, but since gatsby-ssr.js is run on the server, I thought, may as well leverage node for this.