0

I am trying to load dynamically link tag inside a React component with shadow dom, but I can't find a solution to access filename/path with hashes generated by MiniCssExtractPlugin/Webpack.

General idea is to have two+ CSS outputs. First global one and the others for "shadow dom" isolation.

I've already tried to set env variable with filename, but it seems to be async action. My env REACT_APP_CSS is undefined.

// as example
      new MiniCssExtractPlugin({
        filename: ({ chunk }) => {
          // REACT_APP_CSS it is some global variable
          REACT_APP_CSS = `${chunk.name}.${chunk.hash}.css`;
          return `${assetName}.css`;
        }
      }),
    new webpack.DefinePlugin({
        "process.env": JSON.stringify({
          REACT_APP_CSS: REACT_APP_CSS
        })
      }),

Do you happen to know what can I do to access filenames/paths in runtime? Any synchronous solution would be great.

Example component

import root from "react-shadow";
[..]
  return (
  <root.span>
      <link href={myCssPathToBuild} rel="stylesheet" />
    [..]
  </root.span>
)

Hope you can help.

oct51
  • 66
  • 5

1 Answers1

0

I found a solution. It isn't perfect, but it "works".

To access chunks paths you can:

Use assets-webpack-plugin

  new AssetsPlugin({
        filename: "assets.js",
        processOutput: function (assets) {
          return "window.staticMap = " + JSON.stringify(assets);
        }
      }),

It creates a map/object containing pair of chunkName and path. Using AssetPlugin you can specify output and filename with ext. In given example I create js file which set global variable containing asset map.

To access window.staticMap at runtime I included <script src="/assets.js"> in public HTML.

In my humble opinion access to chunks paths should be way much easier. If you have other/better solution, please share.

oct51
  • 66
  • 5