Search code examples
javascriptnode.jssvgrollup

How to handle svg imports (ES6) in rollup


If I'm importing an svg file into an ES6 module, how do I handle that in rollup? I currently have something like this (simple example of what I'm doing):

import next from '../assets/next.svg';
export default () => console.log('Here is some Svg: ! ', next);

And I have a rollup config that looks like this:

import babel from 'rollup-plugin-babel';
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';

export default {
  entry: 'src/app.js',
  dest: 'build/app.min.js',
  format: 'iife',
  sourceMap: 'inline',
  plugins: [
    babel({
      exclude: 'node_modules/**',
    }),
    resolve({
      jsnext: true,
      main: true,
      browser: true,
    }),
    commonjs(),
  ],
};

And then I get the following error:

Could not resolve '../assets/next.svg' from /home/magnferm/projects/slask/rollup-test/src/chill/index.js

There is nothing wrong with the path, but rollup doesn't seem to know how to handle svg-files. Is there a plugin I can use for that or do I have to treat it differently somehow?


Solution

  • There is a plugin for it. It's called @rollup/plugin-image and it handles, among other formats, .svg imports:

    import babel from '@rollup/plugin-babel';
    import resolve from '@rollup/plugin-node-resolve';
    import commonjs from '@rollup/plugin-commonjs';
    import image from '@rollup/plugin-image';
    
    export default {
      entry: 'src/app.js',
      dest: 'build/appn.min.js',
      format: 'iife',
      sourceMap: 'inline',
      plugins: [
        babel({
          exclude: 'node_modules/**',
        }),
        resolve({
          jsnext: true,
          main: true,
          browser: true,
        }),
        commonjs(),
        image()
      ],
    };