PabloRosales JavaScript Developer

Rollup: Adding CSS

Rollup has a very nice long list of plugins for lot of useful things like bundling our CSS, but before we start adding our plugin, lets install something so we can see our HTML in the browser easily. For this we will install http-serve. Run this command in your CLI:

Now lets add our HTML file in src/index.html:

Now lets edit our package.json file so that our index.html file gets copied every time to our dist directory, plus a new script command to serve our our files. This is how the scripts section should look now:

Now we can run two commands, first one to let Rollup watch for our changes and bundle our files:

And the second command to serve our files as bundled by Rollup:

In the previous chapter we where using umd for our bundles, this time we want to use it in the browser with iife so we don't need it to be a module.

Your Rollup config should look something like this:

And your src/index.js file should look like this:

You can open now and see an empty site with the browser/tab title "Rollup Introduction".

Check out the sample code for this part at Rollup Samples.

Lets add some HTML and CSS. First lets change our src/hello.js file to add some HTML:

If you refresh the browser now, you should see a <h1>Hello World</h1> in the page.

Now lets add the CSS, create a file src/typography.css with this content:

And edit our src/index.js file to include it:

You will see that Rollup complains that this is not valid JavaScript code, the error looks something like this:

We can fix this by installed our Rollup CSS plugin and adding it to our config. First lets install rollup-plugin-css-only:

Now we'll add it to our Rollup config file:

Finally we need to add our new bundled index.css to our HTML:

If you run again our command:

You will see that when you refresh the page you get a prettier <h1>Hello World</h1>.

Check out the sample code for this part at Rollup Samples.

Made with by PR