Rollup is a strong module bundler that is great at tree shaking and making efficient code. I will show you how to use Rollup to bundle SASS and JavaScript in a frontend build process.
Prerequisites
You must install Node.js and npm on your computer.
Getting Started
Initialize a new project:
mkdir rollup-sass-js-setup
cd rollup-sass-js-setup
npm init -y
Install the necessary dependencies:
npm install rollup rollup-plugin-sass rollup-plugin-terser --save-dev
Setting up the Rollup Configuration
Create a rollup.config.js
file in the root of your project and set up the configuration:
import sass from 'rollup-plugin-sass';
import { terser } from 'rollup-plugin-terser';
export default {
input: 'src/index.js',
output: {
file: 'dist/bundle.js',
format: 'iife', // Suitable for <script> tags in browsers
},
plugins: [
sass({ output: 'dist/styles.css' }), // Output CSS to a file
terser() // Minify JavaScript
]
};
Setting up the SASS
Let's create a simple SASS file. First, create a src
directory:
mkdir src
Next, create a styles.scss
file inside the src directory:
// src/styles.scss
$primary-color: #3498db;
body {
background-color: $primary-color;
font-family: Arial, sans-serif;
}
Setting up the JavaScript
Create an index.js
file inside the src
directory:
// src/index.js
import './styles.scss';
console.log('Hello, Rollup!');
Setting up the HTML
Create an index.html
file in the root of your project:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Rollup SASS/JS Setup</title>
<link rel="stylesheet" href="dist/styles.css">
</head>
<body>
<script src="dist/bundle.js"></script>
</body>
</html>
Building the Project
Now that everything is set up, you can run Rollup to bundle your JavaScript and compile your SASS:
npx rollup -c
This will generate a bundle.js
and styles.css
in the dist
directory.
Conclusion
Setting up a modern frontend build process with Rollup is straightforward. You can easily bundle your JavaScript and compile your SASS with a few settings. This setup ensures that you have a lean and optimized codebase, ready for deployment. As your project grows, you can add more tools and preprocessors using Rollup's plugin system.
Top comments (1)
Can this plugin minify CSS ?