Skip to content

2.1 Vite Web Application Setup

leonardo1710 edited this page Aug 30, 2023 · 1 revision

Setup a Vanilla TS Application with NPM and Vite

Prerequisites

  • Download and installation of Node.js (v.18.16 or later)
  • Download and install a IDE of your choice (e.g. VSCode)

Setup

Inside your prefered working directory:

npm create vite@latest

Afterwards select Vanilla and TS. This will create a base template for you containing a package.json file, an index.html as an entry point and some .ts and .css files.

Don't forget to install the dependencies first before you run the project:

npm i
npm run dev

Multipage

When using multiple .html files inside your application you need to add some configurations to your Vite project. Suppose you have the following project structure:

├── package.json
├── vite.config.ts
├── index.html
└── src
    ├── main.ts
    └── about
        └── index.html

During development you can simply navigate to /src/about/, since Vite development mode works like a normal static file server. So if you want to add a link from your main index.html to your about/index.html file:

... 
<body>
    <a href="/src/about/">About</a>
    <div id="app"></div>
    <script type="module" src="/src/main.ts"></script>
  </body>

During build you need to declare those .html files as entry points, otherwise the files won't be bundled correctly. Before you go on, try running a build, which bundles your files inside a /dist folder:

npm run build

Checkout your /dist folder.

Afterwards run the following to get a preview of your production-ready application:

npm run preview

The navigation to your about/index.html page will not work.

To define other entry points to your app add a vite.config.ts file in your root repository with the following:

import { resolve } from 'path'
import { defineConfig } from 'vite'

export default defineConfig({
  build: {
    rollupOptions: {
      input: {
        main: resolve(__dirname, 'index.html'),
        about: resolve(__dirname, 'src/about/index.html')
      },
    },
  },
})

Now you might get an error in your IDE saying that Cannot find module 'path' or its corresponding type declarations.. This is because TypeScript needs typings for any module. To solve this problem, you need to install @types/node package, which contains all type definitions for Node.js:

 npm i @types/node -D

Now try and run the build and preview scripts again and don't forget to checkout your freshly created files inside /dist folder.

Linting and Formatting

The next step will demonstrate how to integrate Linting and Formatting with tools like ESLint and Prettier. Those tools help you to set up rules and to enforce code style across your code base.

###Install Dependencies To enable ESLint and Prettier in a vanilla TS project you need to install the following dependencies (as development dependencies):

npm install eslint prettier @typescript-eslint/eslint-plugin @typescript-eslint/parser eslint-config-prettier eslint-plugin-import --save-dev

eslint: the core linter prettier: the core formatter @typescript-eslint/eslint-plugin: an ESLint plugin which provides rules for TypeScript codebases @typescript-eslint/parser: a parser which allows ESLint to lint TypeScript source code eslint-config-prettier: a default configuration which disables the formatting rules in ESLint that Prettier is going to be responsible for eslint-plugin-import: configuration for ESLint of how to resolve imports (ES6+ import/export syntax)

Now we can define a configuration for ESLint. For that create a .eslintrc file in root directory of the project.

{
  "env": {
    "browser": true,
    "node": true
  },
  "settings": {
    // Tells eslint how to resolve imports
    "import/resolver": {
      "node": {
        "paths": ["src"],
        "extensions": [".js", ".jsx", ".ts", ".tsx"]
      }
    }
  },
  "rules": {
    // add your custom rules here
    "no-console": "off",   // disable warnings when logging to console
    "linebreak-style": 0,  // disable LF and CRLF linebreak errors
    "no-plusplus": "off"   // disable no-plusplus errors
  },
  "extends": [
    // By extending from a plugin config, we can get recommended rules without having to add them manually.
    "eslint:recommended",
    "plugin:import/recommended",
    "plugin:@typescript-eslint/recommended",
    // This disables the formatting rules in ESLint that Prettier is going to be responsible for handling.
    // Make sure it's always the last config, so it gets the chance to override other configs.
    "eslint-config-prettier"
  ]
}

Now you can define your own linting rules for your project (ESLint rules).

ESLint ignore file

We only want to lint our source code files and not, for example, node_modules or files inside /dist folder. To do so we can add a eslintignore file and define which files should be ignored by ESLint.

node_modules/
dist/
.prettierrc
.eslintrc
vite-env.d.ts

Run the Linter

To run the linter we must first add an npm script command inside package.json and tell ESLint which files to lint. Additionally, we can add the npm run lint command to our npm run dev to lint on each development start:

{
  "scripts": {
    "dev": "vite",
    "build": "tsc && vite build",
    "preview": "vite preview",
    "lint": "eslint . --ext .ts,.tsx"
  },
}

If you run npm run lint now, you will probably get several linting errors. Those are the enforced linting guidelines from our .eslintrc which need to be fixed. If you like to disable some of them you can edit it in the rules section of your .eslintrc file. Though, it is better to follow the guidelines and fix them.

Configure Prettier

Now that we've taken care of ESLint, let's go ahead and create the .prettierrc file. This is where we specify all of our Prettier formatting rules. Here is an example:

{
  "trailingComma": "all",
  "tabWidth": 2,
  "semi": true,
  "singleQuote": true,
  "printWidth": 120,
  "bracketSpacing": true
}

Here you can find a list of possible Prettier options to configure.

Similar to ESLint you can define a .prettierignore file to disable formatting for specific files and folders:

node_modules/
dist/
.prettierrc

VSCode Extensions

In order to take full advantage of Prettier, you should be using it with an IDE to format your code after you save a file. If you're using VSCode, you can install the Prettier extension. This tutorial gives a detailed overview of how to configure Prettier extension in VSCode.

Use SASS

Sass is an extension (pre-processor) to CSS which will be converted to CSS during build time. Vite provides built-in support for .scss, .sass, .less, .styl and .stylus files. There is no need to install Vite-specific plugins for them, but the corresponding pre-processor itself must be installed, eg in case of SASS (see CSS in Vite):

npm add -D sass

Now you can create a new stylesheet with your preferred syntax (eg. .scss or .sass) and use it out-of-the-box inside your JS and TS files:

/* styles.scss */
$body-color: red;

body {
  color: $body-color;
}
import './style.scss';

// other js code ...

Result should look like this:

image

For more information visit Vite Getting Started

Exercise

  • Setup a project using Vite. Alternatively, you can use another build- and bundling tool of your choice (e.g. Webpack)
  • Configure the project to use Typescript as a primary language (depending on your build tool)
  • Enable code linting and formatting for your project - include a npm script to enforce those rules