Getting Started with Next.js - VSCode, ESLint and Prettier
Tags: vscode, nextjs, javascript, npm
Published: 2021-05-31 16:49:56

# Getting Started with Next.js

*"Next.js gives you the best developer experience with all the features you need for production: hybrid static & server rendering, TypeScript support, smart bundling, route pre-fetching, and more. No config needed."* - as stated on [Next.js home page](https://nextjs.org/).

**Why use Next.js?**
- [Image Optimisation](https://nextjs.org/docs/basic-features/image-optimization)
- [Internationalisation](https://nextjs.org/docs/advanced-features/i18n-routing)
- [Next.js Analytics](https://nextjs.org/analytics)
- [Zero Config](https://nextjs.org/docs/getting-started)
- [Hybrid: SSG and SSR](https://nextjs.org/docs/basic-features/data-fetching)
- [Incremental Static Regeneration](https://nextjs.org/docs/basic-features/data-fetching#incremental-static-regeneration)
- [TypeScript Support](https://nextjs.org/docs/basic-features/typescript)
- [Fast Refresh](https://nextjs.org/docs/basic-features/fast-refresh)
- [File-System Routing](https://nextjs.org/docs/routing/introduction)
- [API Routes](https://nextjs.org/docs/api-routes/introduction)
- [Built-in CSS Support](https://nextjs.org/docs/basic-features/built-in-css-support)
- [Code-Splitting and Bundling](https://nextjs.org/docs/advanced-features/dynamic-import)

## Setting up Next.js

*Note: We will be using [Visual Studio Code](https://code.visualstudio.com/) as a code editor,  but feel free to use any code editor you are most comfortable with when writing code.*

First we need to install some prerequisites:
- [Node.js](https://nodejs.org/en/)
- [yarn](https://yarnpkg.com/) - Package Manager, 

You can also use [npm](https://www.npmjs.com/) as a package manager. In this guide, we will make use of yarn.

We then execute the following command to create a new Next.js app.

```bash
# Replace $PROJECT with your project name
yarn create next-app $PROJECT
# Or using the TypeScript flag for a TypeScript project
yarn create next-app --typescript $PROJECTNAME
```

The previous command will create a basic project. In this newly created project, you will find a file called `package.json`. This file consists of metadata information related to the project, for example; scripts, version and dependencies. 
```json
{
	"name": "$PROJECT",
	"version": "0.1.0",
	"private": true,
	"scripts": {
		"dev": "next dev", 
		"build": "next build",
		"start": "next start"
	},
	"dependencies": {
		"next": "10.2.3",
		"react": "17.0.2",
		"react-dom": "17.0.2"
	}
}
```

The scripts section consists of three different scripts, which when we execute using yarn will: 
- `yarn dev` : Run the application locally
- `yarn build` : Build the application for production
- `yarn start` : Starts the production version of the application

## Liniting using ESLint

We will be using [ESLint](https://eslint.org/) as a linter. The main reasons for using this tool is that; 
- It helps us to catch bugs (by statistically analysing code)
- It helps us to write code in a consistent style

### Installing ESLint extenstion on VSCode

Go to the extensions tab (or use CTRL+SHIFT+X), type in *‘ESLint’* and click install.

![ESLint VS Code Extenstion](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rll8tqc06j6fkm97im29.png)

### Setting up ESLint

To set up ESLint, we need to execute the following command (make sure you're in the root location of the project). 

```bash
# This will add eslint as a dev dependency. 
# If open package.json you will see this new dev dependency added 
# to the project (once executed). 
yarn add eslint --dev
```

The next step is to configure our linter. We need to run the following command to be able to create a new configuration file for ESLint.

```bash
yarn run eslint --init
```

After executing the previous command, you will be prompted with a set of questions. In our set up we selected the following:

- **How would you like to use ESLint?** *To check syntax, find problems, and enforce code style*
- **What types of modules does your project use?** *Javascript modules (import/export)*
- **Which framework does your project use?** *React*
- **Does your project use TypeScript?** *No*  
- **Where does your code run?** *Browser*  
- **How would you like to define a style for your project?** *Use a popular style guide* 
- **Which style guide do you want to follow?** *[Airbnb](https://github.com/airbnb/javascript/tree/master/packages/eslint-config-airbnb) (In this guide we use this style as it is our personal preference)*
- **What format do you want your config file to be in?** *JSON*
- When prompted to install dependencies select ‘yes’.

After answering all the questions, a new file will be created called `.eslintrc.json`. This file holds the configuration for our linter. It is worth noting that we can also specify files that should be ignored by ESLint. This could be done by [creating a `.eslintignore` file](https://eslint.org/docs/user-guide/configuring/ignoring-code). In our projects, we usually ignore the following directories:

``` text
# .estlintignore file
.next
dist
node_modules/
```

*See [Airbnb JavaScript styling guide](https://github.com/airbnb/javascript) and the [ESLint configuration docs](https://eslint.org/docs/user-guide/configuring/#extending-configuration-files) for more information.*

Well done, we managed to set up ESLint using Airbnb’s JavaScript styling guide to our newly created Next.js project. You could have used another popular styling guide like [Google](https://github.com/google/eslint-config-google#readme), [Standard](https://github.com/standard/eslint-config-standard), or even create your own to your liking.

## Formatting using Prettier
We will be using [Prettier](https://prettier.io/) as a code formatter. The main reason for using a code formatter is that it helps us maintain consistency throughout our codebase.

### Installing Prettier extenstion on VSCode

Go to the extensions tab (or use CTRL+SHIFT+X), type in *‘Prettier’* and click install.

![Prettier VS Code Extenstion](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u17xrv1q1xgholdce81z.png "Prettier Extenstion")

Make sure to set `"editor.formatOnSave": true` into your user settings in VSCode to autoformat code when saving a file (CTRL+SHIFT+P -> Open Settings (JSON) -> Paste Configuration). 

### Setting up Prettier

To install prettier to our application, we need to execute the following command:

```bash 
yarn add --dev --exact prettier
```

Next up is to create an empty configuration file for prettier called `.prettierrc.json`. The one shown below is the default configuration we mainly use for our apps, but feel free to [set up your own rules](https://prettier.io/docs/en/options.html). 

```JSON
{
	"singleQuote": true, # Use single quotes instead of double quotes
	"tabWidth": 2, 	     # Number of spaces per indentation level
	"semi": true         # Print semicolons
}
```

Now since some prettier configs may conflict with ESLint, we need to turn off conflicting rules. This can easily be done by [adding `eslint-config-prettier`](https://github.com/prettier/eslint-config-prettier):  
 
```bash 
yarn add --dev eslint-config-prettier
```

Then, add `"prettier"` to the "extends" array in your `.eslintrc.json` file. Make sure to put it **last,** so it gets the chance to override other configs. The file should then look like the one below: 

```JSON
{
	"env": {
		"browser": true,
		"es2021": true
	},
	"extends": ["plugin:react/recommended", "airbnb", "prettier"],
	"parserOptions": {
		"ecmaFeatures": {
			"jsx": true
		},
		"ecmaVersion": 12,
		"sourceType": "module"
	},
	"plugins": ["react"],
	"rules": {}
}
```

Similar to the previous step when configuring ESLint, we may wish to [ignore files from being *“prettified”* in our app](https://prettier.io/docs/en/ignore.html). To do so, create a new file called `.prettierignore`.  

*It is normally advised to base the `.prettierignore` on `.gitignore` and `.eslintignore`*.

Well done, we managed to set up Prettier to our newly created Next.js project to help us maintain consistency throughout our codebase.

### Conclusion

If you made use of Airbnb’s styling guide, you may notice that some JavaScript files which were created when we executed the `create-next-app` command, are highlighted with errors. This is because the code generated by that command does not follow Airbnb’s styling guide conventions. So how do we fix these errors?

- Prop spreading is forbidden [react/jsx-props-no-spreading](https://github.com/yannickcr/eslint-plugin-react/tree/master/docs/rules/jsx-props-no-spreading.md)

	*Explicitly state what props are to be received by the component.*
 
- JSX not allowed in files with extension '.js' [react/jsx-filename-extension](https://github.com/yannickcr/eslint-plugin-react/tree/master/docs/rules/jsx-filename-extension.md)

	*Change file from '.js' to '.jsx'*

- 'React' must be in scope when using JSX [react/react-in-jsx-scope](https://github.com/yannickcr/eslint-plugin-react/tree/master/docs/rules/react-in-jsx-scope.md)

	*Add React import to the file `import React from 'react';`*

- Expected indentation of 2 spaces but found 4 [indent](https://eslint.org/docs/rules/indent): 

	*If you followed the previous steps when configuring the prettier extension, save the file and it will auto-format the code. This issue will be solved, as we set the "tabWidth:2" in `.prettierrc.json`.*


As stated previously, see the [Airbnb styling guide](https://github.com/airbnb/javascript) and [react specific linting rules](https://github.com/yannickcr/eslint-plugin-react), to better understand the errors outputted by the linter. You may also want to [disable specific rules](https://eslint.org/docs/user-guide/configuring/rules#disabling-rules) which are not to your liking or do not follow your coding standards.

**Happy Coding! Feel free to leave any feedback.**