profile
viewpoint

Ask questionsStatic file path returned instead of file content on require('./file.svg')

I'm building a component which loads SVG files. But when I use icon = import() or icon = require(), the value returned is a static-file-path instead of the content of the file.

this.prop.iconName = 'cart' (propType.oneOf)
const icon require(`../assets/svg/${iconName}.svg`)
console.log(icon)

Yields

static/media/cart.67bd7202.svg

The issue https://github.com/storybooks/storybook/issues/1776 is about a similar issue, except that I'm using the full control mode, and I did reset the server. I tried no custom loaders, svg-url-loader, url-loader and file-loader.

My current .storybook/webpack.config.js:

const path = require('path');

module.exports = (baseConfig, env, defaultConfig) => {
    // Extend defaultConfig as you need.

    // For example, add scss loader:
    defaultConfig.module.rules.push({
        test: /\.scss$/,
        loaders: ['style-loader', 'css-loader', 'sass-loader'],
        include: path.resolve(__dirname,'../')
    });
    defaultConfig.resolve.extensions.push('.scss');

    // For example, add SVG loader:
    defaultConfig.module.rules.push({
        test: /\.svg$/,
        loaders: ['svg-url-loader'],
        include: path.resolve(__dirname,'../')
    });
    defaultConfig.resolve.extensions.push('.svg');

    return defaultConfig;
};

Project webpack.config.js:

{
    test: /\.svg$/,
    use: [
        {
            loader: 'svg-url-loader',
            options: {},
         }
    ]
}

"webpack": "^4.27.1",
"webpack-cli": "^3.1.2",
"webpack-dev-server": "^3.1.14"

Command to run storybook locally: "start-storybook -p 9001 -s .storybook/static -c .storybook"

Can anyone help me in the right direction?

storybookjs/storybook

Answer questions adrienjoly

FYI, just adding the following parts in .storybook/webpack.config.js did the trick:

  config.module.rules = config.module.rules.map( data => {
    if (/svg\|/.test( String( data.test ) ))
      data.test = /\.(ico|jpg|jpeg|png|gif|eot|otf|webp|ttf|woff|woff2|cur|ani)(\?.*)?$/;
    return data;
  });

... and:

  config.module.rules.push({
      test: /\.svg$/,
      use: [
        { loader: 'svg-inline-loader' }
      ]
  });

=> I did not need to add .svg in config.resolve.extensions.

Thanks for your help!

useful!
source:https://uonfu.com/
answerer
Adrien Joly adrienjoly @shodoio Montreuil, Paris area, France https://adrienjoly.com/now Senior Software Engineer / Tech Lead. Currently: contractor at SHODO / @signaux-faibles and maintainer of @openwhyd.
Github User Rank List