Skip to content

This Dot Blog

This Dot provides teams with technical leaders who bring deep knowledge of the web platform. We help teams set new standards, and deliver results predictably.

Newest First
Tags:Rollup
Getting Started with LitElement and Tailwind cover image

Getting Started with LitElement and Tailwind

This tooling heavy guide will set you up for a strong start to working with data-driven UI's powered by LitElement, styled by Tailwind's utility CSS classes....

How to Set Up Environment Variables using JSON files with Rollup and TypeScript cover image

How to Set Up Environment Variables using JSON files with Rollup and TypeScript

In previous posts, I explained How to setup a TypeScript project using Rollup.js from scratch. Also, I covered How to Serve a Single Page Application(SPA) using Rollup.js and Web Dev Server step by step. Then, I covered How to Build a LitElement Application with Rollup.js and TypeScript. In this article, I'll take the result of those tutorials as a starting point to set up environment variables using JSON files. Environment Variables Reading environment variables is very common in software development. It's a helpful way to cover security concerns and even provides the convenience to set configuration parameters in your application. For example, in the Node.js world, you may need to set the port number to serve your application. For example: ` In the previous code, the app will read the value of PORT through process.env.PORT. If the value doesn't exist, it will take 3000 as a fallback. JSON Modules In today's JavaScript world, it's possible to read JSON Modules as follows: ` Also, recent versions of Node.js enables the use of --experimental-json-module flag for the module to work. Let's explore a practical way to add the same support to the current Single-Page Application which is based on TypeScript, LitElement, Rollup.js, and Web Dev Server. Project Setup Base Project Let's create a clone or download the project seed before adding the new configurations and tools: ` The previous commands will download the project and create a new branch 04-env-config-json to get started. Source Code Files The previous project already contains a set of files and configurations ready to configure and support JSON Modules. Open it with your favorite code editor and take a look at the project structure: ` Installing Rollup Plugins Since the Single-page application considers Rollup.js as the module bundler, we'll need to install a couple of node modules first: ` * @rollup/plugin-json will be in charge to convert .json files to ES6 modules. * @web/dev-server-rollup is an adapter for using rollup plugins in Web Dev Server, which is used to "serve" the web application in development mode. The package.json file should have the new dependencies listed as follows: ` Reading the JSON Configuration Let's add the following env-config.json file into the root of the project: ` Of course, you can set your variables according to the requirements: access keys, platform, etc. Since you may have sensitive data in that file, it should not be versioned in any case. It's good practice to add it to the .gitignore file: ` Also, you can provide a env-config.json.example file as an example so that developers, Dev Ops, or any member of the team can create a configuration file from it: ` Creating the TypeScript Model It's time to define the TypeScript model for our configurations. First, let's create a src/environment/environment-model.ts: ` Next, create a src/environment/environment.ts file with the following content: ` From now on, the configurations will be available in the env variable. TypeScript Configuration You may see a couple of compilation errors from TypeScript after adding the environment.ts file. To avoid them, it's required to add new compiler options in the tsconfig.json file: ` Why are these changes needed? * The resolveJsonModule flag allows the compiler to include modules with .json extension. * The allowSyntheticDefaultImports flag allows default imports from modules with no default export. As the documentation says, it's just _type checking_. Reading Configuration Values Let's read the configuration values to be rendered into an existing web component. Update the main.ts file with the following content: ` Just pay attention to the import line: import { env } from './environment/environment'. Then the EnvConfig object (TypeScript model) will be available as the env variable. Rollup Configuration As stated above, the project is already configured and uses Rollup as the module bundler. Let's move forward to allow reading the JSON content for the build. ` For every building process, the new json() plugin will be in charge to process the .json files. You can call any other Rollup plugin in the plugins array. Web Dev Server Configuration If you try to serve the application at this point, you'll find a blank page and some errors in the browser's console: ` That is because we configured Rollup for the build process only. However, for serving the app in a "development mode", we're using Web Dev Server. Let's apply a couple of changes in the web-dev-server.config.js file to fix it: ` Let's explain what's happening in that code: * The @web/dev-server-rollup package allows using Rollup plugins in Web Dev Server. * Instead of using json() plugin directly, it needs to be passed through the rollupAdapter function first. When you're done with those changes, run npm run start again to see the final result. Source Code of the Project Find the complete project in this GitHub repository: typescript-rollup. Do not forget to give it a star ⭐️ and play around with the code. Feel free to reach out on Twitter if you have any questions. Follow me on GitHub to see more about my work....

How to Build a LitElement Application with Rollup.js and TypeScript cover image

How to Build a LitElement Application with Rollup.js and TypeScript

In previous posts, I explained How to setup a TypeScript project using Rollup.js from scratch. Also, I covered How to Serve a Single Page Application(SPA) using Rollup.js and Web Dev Server step by step. In this article, I'll take the result of both tutorials as a starting point to integrate LitElement into the game to write the first Web Components through the latest web standards and powerful TypeScript features. Project Setup Prerequisites You'll need to have installed the following tools in your local environment: * Node.js. Preferably the latest LTS version. * A package manager. You can use either NPM or Yarn. This tutorial will use NPM. Initialize the Project Let's create a clone or download the project seed before adding the new configurations and tools: ` The previous commands will download the project and create a new branch 03-litelement-app to get started. Source Code Files The previous project already contains a set of files and configurations ready to go with TypeScript and Rollup. Open it with your favorite code editor and take a look at the project structure: ` Installing LitElement and lit-html The Single-Page Application will be based on LitElement, hence we'll need to install some development dependencies to the project: ` * LitElement will be the main tool for writing the class-based web components for the application. * lit-html is an efficient and extensible HTML templating library. Your package.json file should have the new dependencies listed as follows: ` Rollup Configuration The project is already configured and it uses Rollup as the module bundler. Verify the content of rollup.config.js as follows: ` The baseConfig content will be generated from createSpaConfig function, which is defined in @open-wc/building-rollup package. When createSpaConfig is used, a service worker is generated using Workbox. However, the service worker is injected into the index.html file when the injectServiceWorker flag is enabled. The Serve and Build Scripts Now it's time to pay attention to the package.json file. It already defines a set of scripts to both _serve_ and _build_ the project: ` Let's explain what's going to happen with those scripts: * "tsc:watch" is the script to start with the compilation process through tsc, which is the TypeScript compiler. The --watch param stands for a compiler option to run the compiler in _watch mode_(it trigger recompilation on file changes). * "start" is the script to add the execution of some commands in parallel: npm run tsc:watch and web-dev-server that includes some CLI flags through a configuration file. * You already noted that concurrently command is called first! * The --kill-others parameter will kill all the invoked commands if one dies(either tsc or web-dev-server). It's important to note that any time you need to configure or customize the web-dev-server behavior, the web-dev-server.config.js file should be updated. TypeScript Configuration The TypeScript configuration is defined in tsconfig.json file. It already contains some relevant content for the compilation process: ` However, it would be good to add some capabilities to start working with LitElement. To do that, let's add the experimentalDecorators support along with the dom library(to be included in the compilation process). The final state of this fill would be: ` * "experimentalDecorators": true provides the Decorators support for TypeScript. It involves the use of annotations and meta-programming syntax for class declarations and attributes. LitElement support them too. For example: ` Both @customElement() and @property() decorators will make the web components definition compact. * "lib": "es2017", "dom"] as the name states, provides a configuration with a list of library files to be included in the compilation. Take a look at the [list of possible values for this parameter in the official documentation. Just to clarify, without adding dom into lib configuration, you may find several errors at compilation time. For example: ` Using LitElement Adding the Web Component Definition It's time to add some TypeScript code with the first Web Component through LitElement. Let's create a new file src/main.ts with the following content: ` The previous code defines a new component for your project. You can use it in your template files as if it were a new member of the HTML vocabulary: ` Also, it supports a custom attribute too! ` Update the index.html File At this point, the index.html file of the project defines almost the same content as the Web Component. Let's change the content a little bit: ` Two important things are happening now: * The element will render the brand new component * The tag will load the content of the file that contains the component definition. That's it! You already have a Single-Page Application based on LitElement and TypeScript. Running the Application Run the App in Development mode Serve the application (development mode) using the following command: ` You should see an output with the host and port: ` The default browser will be opened to display the index.html content. Run the Build Version First, run the build command: ` This will generate a dist folder with the following content: ` A simple way to serve these files locally would be to use the http-server tool (a command-line http server): ` The output of this command will show you the host and the port you need to use to access the build version of the app: ` Source Code of the Project Find the complete project in this GitHub repository: typescript-rollup. Do not forget to give it a star ⭐️ and play around with the code. Feel free to reach out on Twitter if you have any questions. Follow me on GitHub to see more about my work....

How to Serve a Single Page Application (SPA) using Rollup.js and Web Dev Server cover image

How to Serve a Single Page Application (SPA) using Rollup.js and Web Dev Server

In a previous post, I explained How to setup a TypeScript project using Rollup.js. In that article, I covered the necessary steps to have a Project Setup ready to generate a build using TypeScript and Rollup configurations. So let's take that project as a starting point to serve a Single-page Application using modern web tools. What is a SPA (Single-page Application)? According to MDN Documentation: > An SPA (single-page application) is a web app implementation that loads only a single web document, and then updates the body content of that single document via JavaScript APIs such as XMLHttpRequest and Fetch when different content is to be shown. A single-page application allows updating only some portions of the current page instead of doing a page refresh. Think about some applications you use every day: * Gmail * Facebook * Twitter * LinkedIn All of these applications have been built with the user experience in mind along with a good loading speed and navigation between pages. There are very good reasons to keep building applications following the SPAs approach. What is Web Dev Server? Web Dev Server, as its name states, it's a web server for development. It helps development using native browser features like ES modules. It has a plugin architecture for code transformations. > Web Dev Server is the successor of es-dev-server It's worth mentioning that Web Dev Server allows configuring auto-reload on file changes along with efficient browser caching for faster reloads. It's configurable and supports rollup plugins too! Project Setup Prerequisites You'll need to have installed the following tools in your local environment: * Node.js. Preferably the latest LTS version. * A package manager. You can use either NPM or Yarn. This tutorial will use NPM. Initialize the Project Let's create a clone or download the project seed before adding the new configurations and tools: ` The previous commands will download the project and create a new branch 02-serve-spa to get started. Source Code Files Once you have the project ready, open it with your favorite code editor and pay attention to the current project structure: ` Installing Web Dev Server and Concurrently Let's add some development dependencies to the project. * Install Web Dev Server ` As I mentioned before, Web Sev Server will be the main tool to configure and run our project this time. Also, if you already know es-dev-server tool, used actively on the Open Web Components initiative, you'll understand that this project migrated to Modern Web website. That does not mean anything other than this new tool continues to be actively developed and can be used in any JavaScript project (TypeScript included ;-)). * Install Concurrently tool ` If you are familiar with any command-line tool, you may have wanted to run commands in parallel. Concurrently has the same goal. However, it's hard to keep track of every command output and concurrently allows you to run any command you want. It's possible to kill all of them if anyone fails. TypeScript Configuration In this case, the tsconfig.json file will remain the same, without any changes: ` Remember, this file is required to be present in the root of any TypeScript project. Rollup Configuration The project is configured to use Rollup as the module bundler. It's possible to run it through command-line parameters. However, if you're looking for advanced functionality, you can consider a rollup.config.js file: ` This file contains a basic configuration. I's needed to set the input files and the output directory for the build. Since we intend to compile a Single-page application now, it will be necessary to apply some changes: ` The baseConfig content will be generated from createSpaConfig, which is defined in @open-wc/building-rollup package. When createSpaConfig is used, a service worker is generated using Workbox. However, the service worker is injected into the index.html file when injectServiceWorker is enabled. HTML file as an Input Once the input parameter is set using an index.html file, any module defined as part of it will be bundled by Rollup. This content will be injected into the HTML file result. The index.html File Let's create an index.html file into the root folder with the following content: ` We can say the content of this file is common. However, the most important line would be the reference to the app.js file: ` Let's explain what is happening there: * As you will remember, the tsconfig.json file sets "outDir": "out-tsc" and that means the TypeScript compiler will generate the output files in ./out-tsc folder. * Then, the index.html file does reference to the entry point of the source code, the compiled version of the ./src/app.ts file. * When the Rollup configuration starts to build the app, it will take the _module_ defined in index.html file to generate a bundle ready for it. Adding Serve and Build Scripts If you pay attention to the package.json file, it already defines a script to generate the build: ` The change we introduced into the rollup.config.json file doesn't affect the build process. Now let's move forward with the addition of some scripts to "serve" the application: ` * "tsc:watch" is the script to start with the compilation process through tsc, which is the TypeScript compiler. The --watch param stands for a compiler option to run the compiler in _watch mode_(it triggers recompilation on file changes). * "start" is the script to add the execution of some commands in parallel: npm run tsc:watch and web-dev-server that includes some CLI flags. * You already noted that concurrently command is called first! * The --kill-others parameter will kill all the invoked commands if one dies (either tsc or web-dev-server). Think for a while how the "start" command is going to look if we're planning to add more configurations in the future: a script that is hard to read and maintain, of course. Adding the web-dev-server.config.js File The alternative option to include the CLI flags as parameters is the creation of the web-dev-server.config.js file. > The file extension can be .js, .cjs or .mjs. A .js file will be loaded as an es module or common js module based on your version of node, and the package type of your project. By default, the Web Dev Server looks at the configuration file in the current working directory. Let's create the web-dev-server.config.js file in the root folder: ` This file now contains the same options we used in the start script with the addition of a custom port number: port: 8000, which can be configured now. For the sake of simplicity, let's update the start script with a reference to the new configuration file: ` That's it! You're ready to serve your first application using: ` You should see the following output: ` Also, your default browser will be opened to display the index.html content. On the right side (when you open the Developer Tools), you'll see the output of the main script file. That is proof that the module is running correctly when the SPA is loaded. Running the Build The script is ready and doesn't need an update. Execute the following command: ` This will generate a dist folder with the following content: ` A simple way to serve these files locally would be to use the http-server tool (a command-line http server): ` The output of this command will show you the host and the port you need to use to access the build version of the app: ` I suggest you review the content of dist/ files and make sure you have http-server installed before running the latest command. Source Code of the Project Find the complete project in this GitHub repository: typescript-rollup. Do not forget to give it a star ⭐️ and play around with the code. Feel free to reach out on Twitter if you have any questions. Follow me on GitHub to see more about my work....

How to Setup a TypeScript project using Rollup.js cover image

How to Setup a TypeScript project using Rollup.js

A couple of months ago, I started to work through web standards, Rollup.js, and TypeScript. It’s my first experience using Rollup although I’ve been working with TypeScript on different projects and using it along other frameworks like Angular. So far, it has been a good experience in terms of performance and tools integration. What is Rollup? In words of the official documentation: > Rollup is a module bundler for JavaScript which compiles small pieces of code into something larger and more complex, such as a library or application... What does that mean? Let’s start by saying that JavaScript improved drastically since ES6, and now it’s possible to define small portions of code that can be shared using two magical keywords: _import_ and _export_. This specification is supported by modern browsers and tools. Rollup allows writing a _future-proof code_ using the new module system without missing the compatibility with other module systems like CommonJS, AMD, and others. Rollup also is considered as the "Next-generation ES module bundler", an alternative to the very known bundler Webpack. Project Setup Let's start building a small application based in TypeScript. Our first goal would be to compile and build it using Rollup. Prerequisites You need to install the following tools in your local environment: * Node.js. Preferably the latest LTS version. * A package manager. You can use either NPM or Yarn. This tutorial will use NPM. Initialize the Project You'll need a new folder to get started, you can create it from a command-line interface or from your favorite IDE/Code Editor: ` Let's start running the first command inside that folder to create the package.json file and have an initialized project. This will be useful to manage and install packages later. ` The previous command will create the package.json with some defaults. You can edit that file later according to your needs: ` Use npm init only if you want to set your preferences with the interactive mode of the command. Source Code Files Let's create a library to perform basic Math operations and perform strings processing. The project will contain the following source files: ` Add the Math operations in math/math.ts file: ` Then, the strings operations will be defined in string/string.ts file: ` In the latest file, we're exporting a function using the ES6 Arrow function expression. In order to import related functions regardless of the filenames, we can create the index.ts files in both directories: ` ` Pay attention to the src/app.ts file: ` The app.ts file is the starting point of our application. Also, take a look at the first import line. We don't need to import those functions from ./math/math.ts file, since all of them have been exported in /math/index.ts file. Again, this is a convenient way to organize the library content using TypeScript. Installing Rollup and TypeScript Let's continue installing Rollup and TypeScript as development dependencies: ` Additional tools are needed: * @open-wc/building-rollup, as a rollup plugin for integration between Rollup.js and TypeScript, * rimraf, which is the UNIX command rm -rf for Node.js * deepmerge, a tool to merge enumerable properties or more objects deeply. Use a single command to have all of them as new dependencies: ` TypeScript Configuration For every TypeScript project, it's required to create the tsconfig.json file. It indicates that the directory is the root of a TypeScript project. ` Let's apply some changes to that file: ` The most important thing here is the outDir option since the value says where the JavaScript files will be generated. Also, the include parameter will list a set of patterns of the files to be included in the compilation. Learn more about the compilerOptions and the tsconfig.json file in TsConfig Reference documentation. Rollup Configuration It's time to configure the module bundler tool: Rollup. You can use Rollup from a command-line interface along with parameters. However, you can provide a configuration file to simplify the usage and provide advanced functionality. Let's create a rollup.config.js file with the next content: ` Take a look at the documentation if you're curious about the different ways to use these configuration files. Also, find an example of the TypeScript support provided by @open-wc/building-rollup package. The Build script In the package.json file, define a script to compile the input files and run the previous configurations: ` Here's what is happening with the script: * rimraf dist, will make sure to clean up the output directory for Rollup: dist * tsc, will run the TypeScript compiler through the configurations defined in tsconfig.json file. The output content will be located in the ./out-tsc directory, as defined in the TypeScript configuration file. * rollup -c rollup.config.json, will run Rollup and take the ./out-tsc directory as input and put the result in a dist folder. Those configurations are defined in the rollup.config.js file. Generate the Build and Run the App Run the build script using: ` You'll have the following output: ` Finally, run the single file generated as a result of the build script: ` You'll see the expected output. The Final Project Structure You should have the following project structure, including the source code files and configurations: ` Alternatives to integrate Rollup and TypeScript In case you're planning to build a SPA project(_Single Page Application_), you can use the createSpaConfig in Rollup configuration. Also, you can install the @rollup/plugin-typescript for seamless integration between Rollup and TypeScript. ` The @rollup/plugin-typescript will load any compilerOptions from the tsconfig.json file by default. However, there's an option to override those configurations: ` In case you prefer a simple configuration, then you can set the rollup.config.js file using only this plugin: ` Or even better, use the open-wc project generator for an automated setup through Rollup, TypeScript, and even Web Components. Source Code of the Project Find the complete project in this GitHub repository: typescript-rollup. Do not forget to give it a star ⭐️ and play around with the code. You can follow me on Twitter and GitHub to see more about my work....