Search code examples
rollupjssveltesvelte-component

Packaging imported javascript into svelte component using rollup


In my code, I want to import an external javascript file that is common across multiple components. When rollup builds the component, however, it has trouble resolving the imported dependency so it never gets included in the output package. Note, I'm trying to build a svelte component (as opposed to a svelte app) although I'm not sure that makes a difference. Here is my rollup.config.js:

import svelte from 'rollup-plugin-svelte';
import pkg from './package.json';

const name = pkg.name
    .replace(/^(@\S+\/)?(svelte-)?(\S+)/, '$3')
    .replace(/^\w/, m => m.toUpperCase())
    .replace(/-\w/g, m => m[1].toUpperCase());

export default {
    input: 'src/Radar.html',
    output: [
        { sourcemap: true, file: pkg.module, 'format': 'es' },
        { sourcemap: true, file: pkg.main, 'format': 'umd', name }
    ],
    plugins: [
        svelte({
            cascade: false,
            store: true
        })
    ]
};

Solution

  • To resolve dependency there is a plugin for Rollup:

    import svelte from 'rollup-plugin-svelte';
    import resolve from '@rollup/plugin-node-resolve';
    import pkg from './package.json';
    
    const name = pkg.name
        .replace(/^(@\S+\/)?(svelte-)?(\S+)/, '$3')
        .replace(/^\w/, m => m.toUpperCase())
        .replace(/-\w/g, m => m[1].toUpperCase());
    
    export default {
        input: 'src/Radar.html',
        output: [
            { sourcemap: true, file: pkg.module, 'format': 'es' },
            { sourcemap: true, file: pkg.main, 'format': 'umd', name }
        ],
        plugins: [
            svelte({
                cascade: false,
                store: true
            }),
            resolve()
        ]
    };
    

    I assume that Radar.html is a Svelte module, i.e. you can rename it to Radar.svelte.