Home > other >  Incorrect implementation of url () path when using webpack
Incorrect implementation of url () path when using webpack

Time:12-26

I ran into this problem:
I am creating a ui library to reuse in another react components project. For many components, the path to the image is specified in the background: url () property.
What the path looks like in the component itself to the webpack:

static/media/src/images/back.svg

But this path is already specified in the reused project (the path must point to the image from node_modules):

http://localhost:3000/static/js/images/back.svg

My goal is to get the image from node_modules and successfully connect it to background: url () of the same component
There are solutions on the Internet when using the resolve-url-loader package, but it is used by the exclusion when SCSS

import React from 'react';
import styled from 'styled-components';

import styles from './UiButton.module.css'

import image from '../../../images/back.svg';

const StyledButton = styled.button`
    color: red;
    background: url(${image});
`;

const UiButton = () => {

    console.log(image);

    return (
        <StyledButton className={styles.button}>Text</StyledButton>
    );
}

export default styled(UiButton)``;

const path = require('path');

module.exports = {
    context: path.resolve(__dirname, 'src'),
    entry: './index.js',
    output: {
        filename: 'index.js',
        path: path.resolve(__dirname, 'dist'),
        clean: true,
        libraryTarget: "umd"
    },
    resolve: {
        extensions: ['.js', '.jsx']
    },
    externals: {
        react: 'react'
    },
    module: {
        rules: [
            {
                test: /\.css/,
                use: ['style-loader', 'css-loader']
            },
            {
                test: /\.(js|jsx)?$/,
                use: ['babel-loader'],
                exclude: /node_modules/
            },
            {
                test: /\.(png|jp(e*)g|svg|gif)$/,
                use: [{
                    loader: 'file-loader',
                    options: {
                        name: 'images/[name].[ext]'
                    },
                }],
            },
        ]
    }
};

CodePudding user response:

Solved the problem using url-loader:

{
    loader: "url-loader",
    options: {
        limit: 8192,
        name: "static/media/[name].[hash:8].[ext]"
     },
 }
  • Related