Search code examples
svelterollupjs

How to set up rollup so that a Svelte project is automatically compiled on save without being served?


In a Svelte project there are already three scripts set up inside the package.json file

"scripts": {
    "build": "rollup -c",
    "dev": "rollup -c -w",
    "start": "sirv public --single"
  },

What I understand from the rollup.config.js file

  • running npm run build compiles the project to the public folder and minifies the files once
  • running npm run dev compiles without minifying and automatically runs npm run start after compilation so the public folder is served and reloaded on change

Since I'm using firebase emulators which includes emulating the hosting and serving of the public directory I'm looking for a way to only automatically compile the Svelte project when saving without the serving ~ how can I achieve this?

EDIT: How can I achieve this by modifying the rollup.config in a way that an additional script e.g. "autobuild": "..." can be added to easily switch between the different modes?


Solution

  • As you can see in the plugins sections of a default Rollup config file for a Svelte project, Rollup conditionally performs the following 3 steps :

        // In dev mode, call `npm run start` once
        // the bundle has been generated
        !production && serve(),
    
        // Watch the `public` directory and refresh the
        // browser on changes when not in production
        !production && livereload('public'),
    
        // If we're building for production (npm run build
        // instead of npm run dev), minify
        production && terser()
    

    In order to prevent your site being automatically served, and your browser automatically refreshed, you can simply comment out the first 2 steps. With the watch flag (-w) still set, your project will still rebuild automatically upon save, provided you started it with npm run dev.

    And if you always want your files minified, you can remove the environment condition in the third step.

    So the end of your plugins section would look like this instead:

        // In dev mode, call `npm run start` once
        // the bundle has been generated
        // !production && serve(),
    
        // Watch the `public` directory and refresh the
        // browser on changes when not in production
        // !production && livereload('public'),
    
        // If we're building for production (npm run build
        // instead of npm run dev), minify
        // production && terser()
        terser()
    

    In addition, if these changes are permanent and you know you will never need to hot serve content, you can remove the serve() function definition near the top of the config file, as well as remove the import statement for rollup-plugin-livereload (which provides the livereload() function).