Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Background image in SCSS with rollup bundle?

I can't able to use image path in scss file as background with rollup bundle.
My rollup config looks like this.

import typescript from 'rollup-plugin-typescript2';
import commonjs from 'rollup-plugin-commonjs';
import external from 'rollup-plugin-peer-deps-external';
import resolve from 'rollup-plugin-node-resolve';
import scss from 'rollup-plugin-scss';
import image from 'rollup-plugin-img'; // module solves image add in source
import pkg from './package.json';

export default {
  input: 'src/index.tsx',
  output: [
    {
      file: pkg.main,
      format: 'cjs',
      exports: 'named',
      sourcemap: true,
    },
    {
      file: pkg.module,
      format: 'es',
      exports: 'named',
      sourcemap: true,
    },
  ],
  plugins: [
    image({
      extensions: /\.(png|jpg|jpeg|gif|svg)$/,
      limit: 10000
    }),
    scss(),
    external(),
    resolve({
      broswer: true
    }),
    typescript({
      rollupCommonJSResolveHack: true,
      exclude: '**/__tests__/**',
      clean: true,
    }),
    commonjs({
      include: ['node_modules/**'],
      namedExports: {
        'node_modules/react/react.js': ['Children', 'Component', 'PropTypes', 'createElement'],
        'node_modules/react-dom/index.js': ['render'],
      },
    })
  ],
};

I am trying to add an image path in scss.

.chipsComponent > div:last-child {
  background: url("/assets/images/Close_Circle.svg") no-repeat;
  background-size: cover;
  height: 16px;
  width: 16px;
  float: right;
  cursor: pointer;
}

image path is adding in browser but rollup is not serving asset folder.Attached screesnhot

The image should show in circled chips(red).
Have I missed anything in rollup config or scss image usage is wrong? Thanks in Advance

like image 901
Vignesh Pushkaran Avatar asked Sep 06 '25 02:09

Vignesh Pushkaran


1 Answers

The scss line below is not actually importing the image:

background: url("/assets/images/Close_Circle.svg") no-repeat;

The rollup plugin rollup-plugin-img relies on resources being used via import declarations, like in a js file:

import logo from './rollup.png';

You have two options:

  1. Write your own SCSS processor plugin that resolves url(...) references to copy over assets into your bundle directory.
  2. Use a more manual rollup plugin like rollup-plugin-copy.

With rollup-plugin-copy you can use the following code in your rollup config:

plugins: [
  copy({
    targets: [
      { src: 'src/assets/images', dest: 'dist/assets/images' },
    ],
  }),

This will copy over all of your images from your source folder to your bundle output.

like image 140
Steakeye Avatar answered Sep 08 '25 12:09

Steakeye