Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bundle only the main component with Svelte

I would like to bundle only the main component in a Svelte application and bootstrap the application myself in a script tag with the container of my choice.

In the Svelte template (rollup and bootstrap), the application is bootstrap in the main.js, which import the App.svelte. I would like bundle only the App.svelte and instanciate the App class myself. The objective is to be able to reuse the app in whatever plateform I want and be able to choose the target (ex: use a component in a CMS, SharePoint, etc.).

So do :

const app = new App({
    target: document.body,
    props: {}
});

myself in a script tag in the index.html

I am novice to webpack and I can't find how to bundle and then call the App class in the index.html

like image 527
PortePoisse Avatar asked Oct 21 '25 03:10

PortePoisse


1 Answers

I finally found what I wanted with the sveltejs/template start project, which use rollup.

In the main.js, delete the instantiation of App class and export that class.

import App from './App.svelte';

export default App;

The rollup build will store the default export of main.js in a variable, named in the rollup.config file ( output -> name ), app by default.

Edit the index.html, deplace the script in the body, and then add a script tag :

<body>
    <div id="app-container"></div>
    <script src='/bundle.js'></script>
    <script>
        var myapp= new app({
            "target": document.getElementById("app-container"),
            "props": {
                "name": 'world'
            }
        })
    </script>
</body>

I removed the defer attribute of the bundle script tag to be sure it is run before.

EDIT - WEBPACK CONFIG

I finally found how to do with webpack, the ouput must be set as a library and the export must be the default (or you must instanciate with new app.default({...}) )

The webpack config edited from the svelte template :

entry: './src/App.svelte',
resolve: {
    alias: {
        svelte: path.resolve('node_modules', 'svelte')
    },
    extensions: ['.mjs', '.js', '.svelte'],
    mainFields: ['svelte', 'browser', 'module', 'main']
},
output: {
    path: __dirname + '/public',
    filename: 'bundle.js',
    chunkFilename: 'bundle.[id].js',
    library: 'app',
    libraryExport: 'default',
    libraryTarget: 'var'
},
...
like image 168
PortePoisse Avatar answered Oct 24 '25 00:10

PortePoisse