Search code examples
cssstorybook

storybook load image from css


I'm trying to run Storybook with a custom Webpack config, and it's putting image files (SVG in this case) in the wrong place; the SVG is output into storybook-static/[filehash].svg, but the CSS is altered to look in static/media/[filename].svg. There is a file there, but its contents are:

module.exports = __webpack_public_path__ + "[filehash].svg";

So for some reason it's putting the CommonJS module in the right place, but the css-loader (or something in the pipeline) is telling it to look at the module instead of the actual file.

Here's my .storyboox/webpack.config.js:

const path = require("path");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");


module.exports = ({ config }) => {
  config.plugins.push(
    new MiniCssExtractPlugin(),
  );

  config.module.rules.push(
    {
      test: /\.(ts|tsx)$/,
      use: [
        {
          loader: require.resolve('ts-loader'),
        },
      ],
    },
    {
      test: /\.(svg|jpe?g|png)$/,
      use: [
        {
          loader: require.resolve('file-loader'),
        },
      ],
    },
    {
      test: /\.scss$/,
      use: [
        MiniCssExtractPlugin.loader,
        // require.resolve("style-loader"),
        {
          loader: require.resolve("css-loader"),
          options: {
            importLoaders: 1,
          },
        },
        {
          loader: require.resolve("sass-loader"),
          options: {
            sourceMap: true,
            data: '$theme-image-path: null;',
          },
        }
      ]
    },
  );

  config.resolve.extensions.push('.ts', '.tsx');

  return config;
};

Solution

  • Fixed it by removing my own file-loader rule (Storybook apparently has its own)