Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output Single HTML File from Svelte Project

I can't find any example anywhere online that shows how to (or if we can) output a single HTML file from a Svelte project using Rollup (not Webpack), containing all CSS and JS injected inline (and not as URLs in script).

like image 817
Sammy Avatar asked May 02 '20 19:05

Sammy


1 Answers

There is no built-in way to achieve this, so you'll have to write your own plugin to do so. This code is some sort of an attemt to get this done and could act as a starter point. It is in no way actually complete or good. (to be honest I doubt you will be winning any sort of performance with this approach)

import svelte from 'rollup-plugin-svelte';
import fs from 'fs';
import path from 'path';

function inlineSvelte(template, dest) {
    return {
        name: 'Svelte Inliner',
        generateBundle(opts, bundle) {
            const file = path.parse(opts.file).base
            const code = bundle[file].code
            const output = fs.readFileSync(template, 'utf-8')
            bundle[file].code = output.replace('%%script%%', () => code)
        }
    }
}

export default {
    input: 'src/main.js',
    output: {
        format: 'iife',
        file: './public/index.html',
        name: 'app'
    },
    plugins: [
        svelte({
        }),
        inlineSvelte('./src/template.html')
    ]
};

This will rely on a template.html file that in it's most basic would like this

<html>
    <head>
        <script>%%script%%</script>
    </head>
    <body></body>
</html>
like image 97
Stephane Vanraes Avatar answered Sep 25 '22 13:09

Stephane Vanraes