Unverified Commit 7a1c9eb1 authored by Houssein Djirdeh's avatar Houssein Djirdeh Committed by GitHub

[ESLint] Introduce a new setup process when `next lint` is run for the first time (#26584)

This PR introduces an improved developer experience when `next lint` is run for the first time.

### Current behavior

`eslint-config-next` is a required package that must be installed before proceeding with `next lint` or `next build`:

![image](https://user-images.githubusercontent.com/12476932/123468791-43088100-d5c0-11eb-9ad0-5beb80b6c968.png)

Although this has helped many developers start using the new ESLint config, this has also resulted in a few issues:

- Users are required to install the full config (`eslint-config-next`) even if they do not use it or use the Next.js plugin directly (`eslint-plugin-next`).
  - #26348

- There's some confusion  on why `eslint-config-next` needs to be installed or how it should be used instead of `eslint-plugin-next`.
  - #26574
  - #26475
  - #26438

### New behavior

Instead of enforcing `eslint-config-next` as a required package, this PR prompts the user by asking what config they would like to start. This happens when `next lint` is run for the first time **and** if no ESLint configuration is detected in the application.

<img src="https://user-images.githubusercontent.com/12476932/124331177-e1668a80-db5c-11eb-8915-38d3dc20f5d4.gif" width="800" />

- The CLI will take care of installing `eslint` or `eslint-config-next` if either is not already installed
- Users now have the option to choose between a strict configuration (`next/core-web-vitals`) or just the base configuration (`next`)
- For users that decide to create their own ESLint configuration, or already have an existing one, **installing `eslint-config-next` will not be a requirement for `next lint` or `next build` to run**. A warning message will just show if the Next.js ESLint plugin is not detected in an ESLint config. 

  <img width="682" alt="Screen Shot 2021-06-25 at 3 02 12 PM" src="https://user-images.githubusercontent.com/12476932/123473329-6cc4a680-d5c6-11eb-9a57-d5c0b89a2732.png">

---

In addition, this PR also:

- Fixes #26348
- Updates documentation to make it more clear what approach to take for new and existing ESLint configurations
parent 8724352b
...@@ -18,63 +18,67 @@ Then run `npm run lint` or `yarn lint`: ...@@ -18,63 +18,67 @@ Then run `npm run lint` or `yarn lint`:
yarn lint yarn lint
``` ```
If you don't already have ESLint configured in your application, you will be guided through the installation of the required packages. If you don't already have ESLint configured in your application, you will be guided through the installation and configuration process.
```bash ```bash
yarn lint yarn lint
# You'll see instructions like these: # You'll see a prompt like this:
# #
# Please install eslint and eslint-config-next by running: # ? How would you like to configure ESLint?
# #
# yarn add --dev eslint eslint-config-next # ❯ Base configuration + Core Web Vitals rule-set (recommended)
# # Base configuration
# ... # None
``` ```
If no ESLint configuration is present, Next.js will create an `.eslintrc` file in the root of your project and automatically configure it with the base configuration: One of the following three options can be selected:
```js - **Strict**: Includes Next.js' base ESLint configuration along with a stricter [Core Web Vitals rule-set](/docs/basic-features/eslint.md#core-web-vitals). This is the recommended configuration for developers setting up ESLint for the first time.
{
```json
{
"extends": "next/core-web-vitals"
}
```
- **Base**: Includes Next.js' base ESLint configuration.
```json
{
"extends": "next" "extends": "next"
} }
``` ```
You can now run `next lint` every time you want to run ESLint to catch errors. - **Cancel**: Does not include any ESLint configuration. Only select this option if you plan on setting up your own custom ESLint configuration.
> The default base configuration (`"extends": "next"`) can be updated at any time and will only be included if no ESLint configuration is present. If either of the two configuration options are selected, Next.js will automatically install `eslint` and `eslint-config-next` as development dependencies in your application and create an `.eslintrc.json` file in the root of your project that includes your selected configuration.
We recommend using an appropriate [integration](https://eslint.org/docs/user-guide/integrations#editors) to view warnings and errors directly in your code editor during development. You can now run `next lint` every time you want to run ESLint to catch errors. Once ESLint has been set up, it will also automatically run during every build (`next build`). Errors will fail the build, while warnings will not.
## Linting During Builds > If you do not want ESLint to run during `next build`, refer to the documentation for [Ignoring ESLint](/docs/api-reference/next.config.js/ignoring-eslint.md).
Once ESLint has been set up, it will automatically run during every build (`next build`). Errors will fail the build, while warnings will not. We recommend using an appropriate [integration](https://eslint.org/docs/user-guide/integrations#editors) to view warnings and errors directly in your code editor during development.
If you do not want ESLint to run as a build step, refer to the documentation for [Ignoring ESLint](/docs/api-reference/next.config.js/ignoring-eslint.md): ## ESLint Config
## Linting Custom Directories The default configuration (`eslint-config-next`) includes everything you need to have an optimal out-of-the-box linting experience in Next.js. If you do not have ESLint already configured in your application, we recommend using `next lint` to set up ESLint along with this configuration.
By default, Next.js will run ESLint for all files in the `pages/`, `components/`, and `lib/` directories. However, you can specify which directories using the `dirs` option in the `eslint` config in `next.config.js`: > If you would like to use `eslint-config-next` along with other ESLint configurations, refer to the [Additional Configurations](/docs/basic-features/eslint.md#additional-configurations) section to learn how to do so without causing any conflicts.
```js Recommended rule-sets from the following ESLint plugins are all used within `eslint-config-next`:
module.exports = {
eslint: {
dirs: ['pages', 'utils'], // Only run ESLint on the 'pages' and 'utils' directories (next build and next lint)
},
}
```
Also, the `--dir` flag can be used for `next lint`: - [`eslint-plugin-react`](https://www.npmjs.com/package/eslint-plugin-react)
- [`eslint-plugin-react-hooks`](https://www.npmjs.com/package/eslint-plugin-react-hooks)
- [`eslint-plugin-next`](https://www.npmjs.com/package/@next/eslint-plugin-next)
```bash You can see the full details of the shareable configuration in the [`eslint-config-next`](https://www.npmjs.com/package/eslint-config-next) package.
yarn lint --dir pages --dir utils
```
This will take precedence over the configuration from `next.config.js`. This will take precedence over the configuration from `next.config.js`.
## ESLint Plugin ## ESLint Plugin
Next.js provides an ESLint plugin, [`eslint-plugin-next`](https://www.npmjs.com/package/@next/eslint-plugin-next), making it easier to catch common issues and problems in a Next.js application. The full set of rules is as follows: Next.js provides an ESLint plugin, [`eslint-plugin-next`](https://www.npmjs.com/package/@next/eslint-plugin-next), already bundled within the base configuration that makes it possible to catch common issues and problems in a Next.js application. The full set of rules is as follows:
| | Rule | Description | | | Rule | Description |
| :-: | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | | :-: | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
...@@ -94,34 +98,36 @@ Next.js provides an ESLint plugin, [`eslint-plugin-next`](https://www.npmjs.com/ ...@@ -94,34 +98,36 @@ Next.js provides an ESLint plugin, [`eslint-plugin-next`](https://www.npmjs.com/
- ✔: Enabled in the recommended configuration - ✔: Enabled in the recommended configuration
## Base Configuration If you already have ESLint configured in your application, we recommend extending from this plugin directly instead of including `eslint-config-next` unless a few conditions are met. Refer to the [Recommended Plugin Ruleset](/docs/basic-features/eslint.md#recommended-plugin-ruleset) to learn more.
## Linting Custom Directories
The Next.js base ESLint configuration is automatically generated when `next lint` is run for the first time: By default, Next.js will run ESLint for all files in the `pages/`, `components/`, and `lib/` directories. However, you can specify which directories using the `dirs` option in the `eslint` config in `next.config.js` for production builds:
```js ```js
{ module.exports = {
"extends": "next" eslint: {
dirs: ['pages', 'utils'], // Only run ESLint on the 'pages' and 'utils' directories during production builds (next build)
},
} }
``` ```
This configuration extends recommended rule sets from various ESLint plugins: Similarly, the `--dir` flag can be used for `next lint`:
- [`eslint-plugin-react`](https://www.npmjs.com/package/eslint-plugin-react)
- [`eslint-plugin-react-hooks`](https://www.npmjs.com/package/eslint-plugin-react-hooks)
- [`eslint-plugin-next`](https://www.npmjs.com/package/@next/eslint-plugin-next)
You can see the full details of the shareable configuration in the [`eslint-config-next`](https://www.npmjs.com/package/eslint-config-next) package. ```bash
next lint --dir pages --dir utils
```
## Disabling Rules ## Disabling Rules
If you would like to modify or disable any rules provided by the supported plugins (`react`, `react-hooks`, `next`), you can directly change them using the `rules` property in your `.eslintrc`: If you would like to modify or disable any rules provided by the supported plugins (`react`, `react-hooks`, `next`), you can directly change them using the `rules` property in your `.eslintrc`:
```js ```json
{ {
"extends": "next", "extends": "next",
"rules": { "rules": {
"react/no-unescaped-entities": "off", "react/no-unescaped-entities": "off",
"@next/next/no-page-custom-font": "off", "@next/next/no-page-custom-font": "off"
} }
} }
``` ```
...@@ -140,23 +146,23 @@ If you would like to modify or disable any rules provided by the supported plugi ...@@ -140,23 +146,23 @@ If you would like to modify or disable any rules provided by the supported plugi
### Core Web Vitals ### Core Web Vitals
A stricter `next/core-web-vitals` rule set can also be added in `.eslintrc`: The `next/core-web-vitals` rule set is enabled when `next lint` is run for the first time and the **strict** option is selected.
``` ```json
{ {
"extends": ["next", "next/core-web-vitals"] "extends": "next/core-web-vitals"
} }
``` ```
`next/core-web-vitals` updates `eslint-plugin-next` to error on a number of rules that are warnings by default if they affect [Core Web Vitals](https://web.dev/vitals/). `next/core-web-vitals` updates `eslint-plugin-next` to error on a number of rules that are warnings by default if they affect [Core Web Vitals](https://web.dev/vitals/).
> Both `next` and `next/core-web-vitals` entry points are automatically included for new applications built with [Create Next App](/docs/api-reference/create-next-app.md). > The `next/core-web-vitals` entry point is automatically included for new applications built with [Create Next App](/docs/api-reference/create-next-app.md).
## Usage with Prettier ## Usage with Prettier
ESLint also contains code formatting rules, which can conflict with your existing [Prettier](https://prettier.io/) setup. We recommend including [eslint-config-prettier](https://github.com/prettier/eslint-config-prettier) in your ESLint config to make ESLint and Prettier work together. ESLint also contains code formatting rules, which can conflict with your existing [Prettier](https://prettier.io/) setup. We recommend including [eslint-config-prettier](https://github.com/prettier/eslint-config-prettier) in your ESLint config to make ESLint and Prettier work together.
```js ```json
{ {
"extends": ["next", "prettier"] "extends": ["next", "prettier"]
} }
......
...@@ -256,7 +256,7 @@ export async function createApp({ ...@@ -256,7 +256,7 @@ export async function createApp({
rename: (name) => { rename: (name) => {
switch (name) { switch (name) {
case 'gitignore': case 'gitignore':
case 'eslintrc': { case 'eslintrc.json': {
return '.'.concat(name) return '.'.concat(name)
} }
// README.md is ignored by webpack-asset-relocator-loader used by ncc: // README.md is ignored by webpack-asset-relocator-loader used by ncc:
......
{
"extends": ["next", "next/core-web-vitals"]
}
{
"extends": ["next", "next/core-web-vitals"]
}
...@@ -39,6 +39,7 @@ const nextLint: cliCommand = async (argv) => { ...@@ -39,6 +39,7 @@ const nextLint: cliCommand = async (argv) => {
'--help': Boolean, '--help': Boolean,
'--base-dir': String, '--base-dir': String,
'--dir': [String], '--dir': [String],
'--strict': Boolean,
// Aliases // Aliases
'-h': '--help', '-h': '--help',
...@@ -100,6 +101,9 @@ const nextLint: cliCommand = async (argv) => { ...@@ -100,6 +101,9 @@ const nextLint: cliCommand = async (argv) => {
--ext [String] Specify JavaScript file extensions - default: .js, .jsx, .ts, .tsx --ext [String] Specify JavaScript file extensions - default: .js, .jsx, .ts, .tsx
--resolve-plugins-relative-to path::String A folder where plugins should be resolved from, CWD by default --resolve-plugins-relative-to path::String A folder where plugins should be resolved from, CWD by default
Initial setup:
--strict Creates an .eslintrc.json file using the Next.js strict configuration (only possible if no .eslintrc.json file is present)
Specifying rules: Specifying rules:
--rulesdir [path::String] Use additional rules from this directory --rulesdir [path::String] Use additional rules from this directory
...@@ -156,6 +160,7 @@ const nextLint: cliCommand = async (argv) => { ...@@ -156,6 +160,7 @@ const nextLint: cliCommand = async (argv) => {
const reportErrorsOnly = Boolean(args['--quiet']) const reportErrorsOnly = Boolean(args['--quiet'])
const maxWarnings = args['--max-warnings'] ?? -1 const maxWarnings = args['--max-warnings'] ?? -1
const formatter = args['--format'] || null const formatter = args['--format'] || null
const strict = Boolean(args['--strict'])
runLintCheck( runLintCheck(
baseDir, baseDir,
...@@ -164,7 +169,8 @@ const nextLint: cliCommand = async (argv) => { ...@@ -164,7 +169,8 @@ const nextLint: cliCommand = async (argv) => {
eslintOptions(args), eslintOptions(args),
reportErrorsOnly, reportErrorsOnly,
maxWarnings, maxWarnings,
formatter formatter,
strict
) )
.then(async (lintResults) => { .then(async (lintResults) => {
const lintOutput = const lintOutput =
...@@ -193,7 +199,7 @@ const nextLint: cliCommand = async (argv) => { ...@@ -193,7 +199,7 @@ const nextLint: cliCommand = async (argv) => {
if (lintOutput) { if (lintOutput) {
console.log(lintOutput) console.log(lintOutput)
} else { } else if (lintResults && !lintOutput) {
console.log(chalk.green('✔ No ESLint warnings or errors')) console.log(chalk.green('✔ No ESLint warnings or errors'))
} }
}) })
......
MIT License
Copyright (c) 2018 Cyril Wanner
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
module.exports=(()=>{"use strict";var e={610:(e,t)=>{Object.defineProperty(t,"__esModule",{value:true});t.withPromise=t.withCallback=void 0;const r=(e,t,r)=>{e.open();e.onSelect((e,s)=>r(t(e,s)))};t.withCallback=r;const s=(e,t)=>{return new Promise((r,s)=>{e.open();e.onSelect((e,i)=>{if(e===null){s()}else{r(t(e,i))}})})};t.withPromise=s},960:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:true});t.default=void 0;var s=_interopRequireDefault(r(213));var i=_interopRequireDefault(r(88));var n=r(610);var u=r(797);function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function _objectSpread(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};var s=Object.keys(r);if(typeof Object.getOwnPropertySymbols==="function"){s=s.concat(Object.getOwnPropertySymbols(r).filter(function(e){return Object.getOwnPropertyDescriptor(r,e).enumerable}))}s.forEach(function(t){_defineProperty(e,t,r[t])})}return e}function _defineProperty(e,t,r){if(t in e){Object.defineProperty(e,t,{value:r,enumerable:true,configurable:true,writable:true})}else{e[t]=r}return e}const o={outputStream:process.stdout,inputStream:process.stdin,values:[],defaultValue:0,selected:"(x)",unselected:"( )",indentation:0,cleanup:true,valueRenderer:e=>e};const a=(e,t)=>{e=_objectSpread({},o,e);const r=new i.default(e,e.outputStream);const a=new s.default(e.inputStream);a.setDefaultValue(e.defaultValue);a.attachRenderer(r);let l;if(Array.isArray(e.values)){l=(0,u.withArrayValues)(e)}else{l=(0,u.withObjectValues)(e)}e.values=l.input;a.setValues(e.values);if(typeof t==="function"){return(0,n.withCallback)(a,l.output,t)}else{return(0,n.withPromise)(a,l.output)}};t=e.exports=a;Object.defineProperty(t,"__esModule",{value:true});var l=a;t.default=l},213:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:true});t.default=void 0;var s=_interopRequireDefault(r(58));function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}class Input{constructor(e=process.stdin){this.stream=e;this.values=[];this.selectedValue=0;this.onSelectListener=(()=>{});this.onKeyPress=this.onKeyPress.bind(this)}setValues(e){this.values=e;if(this.renderer){this.renderer.setValues(e)}}setDefaultValue(e){this.selectedValue=e}attachRenderer(e){this.renderer=e;this.renderer.setValues(this.values)}onSelect(e){this.onSelectListener=e}open(){s.default.emitKeypressEvents(this.stream);this.stream.on("keypress",this.onKeyPress);if(this.renderer){this.renderer.render(this.selectedValue)}this.stream.setRawMode(true);this.stream.resume()}close(e=false){this.stream.setRawMode(false);this.stream.pause();if(this.renderer){this.renderer.cleanup()}if(e){this.onSelectListener(null)}else{this.onSelectListener(this.selectedValue,this.values[this.selectedValue])}this.stream.removeListener("keypress",this.onKeyPress)}render(){if(!this.renderer){return}this.renderer.render(this.selectedValue)}onKeyPress(e,t){if(t){if(t.name==="up"&&this.selectedValue>0){this.selectedValue--;this.render()}else if(t.name==="down"&&this.selectedValue+1<this.values.length){this.selectedValue++;this.render()}else if(t.name==="return"){this.close()}else if(t.name==="escape"||t.name==="c"&&t.ctrl){this.close(true)}}}}t.default=Input},88:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:true});t.default=void 0;var s=_interopRequireDefault(r(58));var i=r(211);function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}class Renderer{constructor(e,t=process.stdout){this.options=e;this.stream=t;this.values=[];this.initialRender=true}setValues(e){this.values=e}render(e=0){if(this.initialRender){this.initialRender=false;this.stream.write(i.cursorHide)}else{this.stream.write((0,i.eraseLines)(this.values.length))}this.values.forEach((t,r)=>{const s=e===r?this.options.selected:this.options.unselected;const i=" ".repeat(this.options.indentation);const n=this.options.valueRenderer(t,e===r);const u=r!==this.values.length-1?"\n":"";this.stream.write(i+s+" "+n+u)})}cleanup(){this.stream.write((0,i.eraseLines)(this.values.length));this.stream.write(i.cursorShow)}}t.default=Renderer},797:(e,t)=>{Object.defineProperty(t,"__esModule",{value:true});t.withObjectValues=t.withArrayValues=void 0;const r=e=>{return{input:e.values,output:(e,t)=>{return{id:e,value:t}}}};t.withArrayValues=r;const s=e=>{const t=e.values;return{input:Object.values(t),output:(e,r)=>{return{id:Object.keys(t)[e],value:r}}}};t.withObjectValues=s},211:e=>{const t=e.exports;const r="[";const s="]";const i="";const n=";";const u=process.env.TERM_PROGRAM==="Apple_Terminal";t.cursorTo=((e,t)=>{if(typeof e!=="number"){throw new TypeError("The `x` argument is required")}if(typeof t!=="number"){return r+(e+1)+"G"}return r+(t+1)+";"+(e+1)+"H"});t.cursorMove=((e,t)=>{if(typeof e!=="number"){throw new TypeError("The `x` argument is required")}let s="";if(e<0){s+=r+-e+"D"}else if(e>0){s+=r+e+"C"}if(t<0){s+=r+-t+"A"}else if(t>0){s+=r+t+"B"}return s});t.cursorUp=(e=>r+(typeof e==="number"?e:1)+"A");t.cursorDown=(e=>r+(typeof e==="number"?e:1)+"B");t.cursorForward=(e=>r+(typeof e==="number"?e:1)+"C");t.cursorBackward=(e=>r+(typeof e==="number"?e:1)+"D");t.cursorLeft=r+"G";t.cursorSavePosition=r+(u?"7":"s");t.cursorRestorePosition=r+(u?"8":"u");t.cursorGetPosition=r+"6n";t.cursorNextLine=r+"E";t.cursorPrevLine=r+"F";t.cursorHide=r+"?25l";t.cursorShow=r+"?25h";t.eraseLines=(e=>{let r="";for(let s=0;s<e;s++){r+=t.eraseLine+(s<e-1?t.cursorUp():"")}if(e){r+=t.cursorLeft}return r});t.eraseEndLine=r+"K";t.eraseStartLine=r+"1K";t.eraseLine=r+"2K";t.eraseDown=r+"J";t.eraseUp=r+"1J";t.eraseScreen=r+"2J";t.scrollUp=r+"S";t.scrollDown=r+"T";t.clearScreen="c";t.clearTerminal=process.platform==="win32"?`${t.eraseScreen}${r}0f`:`${t.eraseScreen}${r}3J${r}H`;t.beep=i;t.link=((e,t)=>{return[s,"8",n,n,t,i,e,s,"8",n,n,i].join("")});t.image=((e,t)=>{t=t||{};let r=s+"1337;File=inline=1";if(t.width){r+=`;width=${t.width}`}if(t.height){r+=`;height=${t.height}`}if(t.preserveAspectRatio===false){r+=";preserveAspectRatio=0"}return r+":"+e.toString("base64")+i});t.iTerm={};t.iTerm.setCwd=(e=>s+"50;CurrentDir="+(e||process.cwd())+i)},58:e=>{e.exports=require("readline")}};var t={};function __nccwpck_require__(r){if(t[r]){return t[r].exports}var s=t[r]={exports:{}};var i=true;try{e[r](s,s.exports,__nccwpck_require__);i=false}finally{if(i)delete t[r]}return s.exports}__nccwpck_require__.ab=__dirname+"/";return __nccwpck_require__(960)})();
\ No newline at end of file
{"name":"cli-select","main":"index.js","author":"Cyril Wanner <info@cyr.li>","license":"MIT"}
The MIT License (MIT)
Copyright (c) 2018 Made With MOXY Lda <hello@moxy.studio>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
module.exports=(()=>{var e={875:(e,t,r)=>{"use strict";const n=r(129);const o=r(915);const s=r(985);function spawn(e,t,r){const c=o(e,t,r);const i=n.spawn(c.command,c.args,c.options);s.hookChildProcess(i,c);return i}function spawnSync(e,t,r){const c=o(e,t,r);const i=n.spawnSync(c.command,c.args,c.options);i.error=i.error||s.verifyENOENTSync(i.status,c);return i}e.exports=spawn;e.exports.spawn=spawn;e.exports.sync=spawnSync;e.exports._parse=o;e.exports._enoent=s},985:e=>{"use strict";const t=process.platform==="win32";function notFoundError(e,t){return Object.assign(new Error(`${t} ${e.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${t} ${e.command}`,path:e.command,spawnargs:e.args})}function hookChildProcess(e,r){if(!t){return}const n=e.emit;e.emit=function(t,o){if(t==="exit"){const t=verifyENOENT(o,r,"spawn");if(t){return n.call(e,"error",t)}}return n.apply(e,arguments)}}function verifyENOENT(e,r){if(t&&e===1&&!r.file){return notFoundError(r.original,"spawn")}return null}function verifyENOENTSync(e,r){if(t&&e===1&&!r.file){return notFoundError(r.original,"spawnSync")}return null}e.exports={hookChildProcess:hookChildProcess,verifyENOENT:verifyENOENT,verifyENOENTSync:verifyENOENTSync,notFoundError:notFoundError}},915:(e,t,r)=>{"use strict";const n=r(622);const o=r(458);const s=r(921);const c=r(266);const i=r(217);const a=r(519);const u=process.platform==="win32";const f=/\.(?:com|exe)$/i;const l=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;const p=o(()=>a.satisfies(process.version,"^4.8.0 || ^5.7.0 || >= 6.0.0",true))||false;function detectShebang(e){e.file=s(e);const t=e.file&&i(e.file);if(t){e.args.unshift(e.file);e.command=t;return s(e)}return e.file}function parseNonShell(e){if(!u){return e}const t=detectShebang(e);const r=!f.test(t);if(e.options.forceShell||r){const r=l.test(t);e.command=n.normalize(e.command);e.command=c.command(e.command);e.args=e.args.map(e=>c.argument(e,r));const o=[e.command].concat(e.args).join(" ");e.args=["/d","/s","/c",`"${o}"`];e.command=process.env.comspec||"cmd.exe";e.options.windowsVerbatimArguments=true}return e}function parseShell(e){if(p){return e}const t=[e.command].concat(e.args).join(" ");if(u){e.command=typeof e.options.shell==="string"?e.options.shell:process.env.comspec||"cmd.exe";e.args=["/d","/s","/c",`"${t}"`];e.options.windowsVerbatimArguments=true}else{if(typeof e.options.shell==="string"){e.command=e.options.shell}else if(process.platform==="android"){e.command="/system/bin/sh"}else{e.command="/bin/sh"}e.args=["-c",t]}return e}function parse(e,t,r){if(t&&!Array.isArray(t)){r=t;t=null}t=t?t.slice(0):[];r=Object.assign({},r);const n={command:e,args:t,options:r,file:undefined,original:{command:e,args:t}};return r.shell?parseShell(n):parseNonShell(n)}e.exports=parse},266:e=>{"use strict";const t=/([()\][%!^"`<>&|;, *?])/g;function escapeCommand(e){e=e.replace(t,"^$1");return e}function escapeArgument(e,r){e=`${e}`;e=e.replace(/(\\*)"/g,'$1$1\\"');e=e.replace(/(\\*)$/,"$1$1");e=`"${e}"`;e=e.replace(t,"^$1");if(r){e=e.replace(t,"^$1")}return e}e.exports.command=escapeCommand;e.exports.argument=escapeArgument},217:(e,t,r)=>{"use strict";const n=r(747);const o=r(598);function readShebang(e){const t=150;let r;if(Buffer.alloc){r=Buffer.alloc(t)}else{r=new Buffer(t);r.fill(0)}let s;try{s=n.openSync(e,"r");n.readSync(s,r,0,t,0);n.closeSync(s)}catch(e){}return o(r.toString())}e.exports=readShebang},921:(e,t,r)=>{"use strict";const n=r(622);const o=r(753);const s=r(226)();function resolveCommandAttempt(e,t){const r=process.cwd();const c=e.options.cwd!=null;if(c){try{process.chdir(e.options.cwd)}catch(e){}}let i;try{i=o.sync(e.command,{path:(e.options.env||process.env)[s],pathExt:t?n.delimiter:undefined})}catch(e){}finally{process.chdir(r)}if(i){i=n.resolve(c?e.options.cwd:"",i)}return i}function resolveCommand(e){return resolveCommandAttempt(e)||resolveCommandAttempt(e,true)}e.exports=resolveCommand},226:e=>{"use strict";e.exports=(e=>{e=e||{};const t=e.env||process.env;const r=e.platform||process.platform;if(r!=="win32"){return"PATH"}return Object.keys(t).find(e=>e.toUpperCase()==="PATH")||"Path"})},607:(e,t,r)=>{var n=r(747);var o;if(process.platform==="win32"||global.TESTING_WINDOWS){o=r(750)}else{o=r(821)}e.exports=isexe;isexe.sync=sync;function isexe(e,t,r){if(typeof t==="function"){r=t;t={}}if(!r){if(typeof Promise!=="function"){throw new TypeError("callback not provided")}return new Promise(function(r,n){isexe(e,t||{},function(e,t){if(e){n(e)}else{r(t)}})})}o(e,t||{},function(e,n){if(e){if(e.code==="EACCES"||t&&t.ignoreErrors){e=null;n=false}}r(e,n)})}function sync(e,t){try{return o.sync(e,t||{})}catch(e){if(t&&t.ignoreErrors||e.code==="EACCES"){return false}else{throw e}}}},821:(e,t,r)=>{e.exports=isexe;isexe.sync=sync;var n=r(747);function isexe(e,t,r){n.stat(e,function(e,n){r(e,e?false:checkStat(n,t))})}function sync(e,t){return checkStat(n.statSync(e),t)}function checkStat(e,t){return e.isFile()&&checkMode(e,t)}function checkMode(e,t){var r=e.mode;var n=e.uid;var o=e.gid;var s=t.uid!==undefined?t.uid:process.getuid&&process.getuid();var c=t.gid!==undefined?t.gid:process.getgid&&process.getgid();var i=parseInt("100",8);var a=parseInt("010",8);var u=parseInt("001",8);var f=i|a;var l=r&u||r&a&&o===c||r&i&&n===s||r&f&&s===0;return l}},750:(e,t,r)=>{e.exports=isexe;isexe.sync=sync;var n=r(747);function checkPathExt(e,t){var r=t.pathExt!==undefined?t.pathExt:process.env.PATHEXT;if(!r){return true}r=r.split(";");if(r.indexOf("")!==-1){return true}for(var n=0;n<r.length;n++){var o=r[n].toLowerCase();if(o&&e.substr(-o.length).toLowerCase()===o){return true}}return false}function checkStat(e,t,r){if(!e.isSymbolicLink()&&!e.isFile()){return false}return checkPathExt(t,r)}function isexe(e,t,r){n.stat(e,function(n,o){r(n,n?false:checkStat(o,e,t))})}function sync(e,t){return checkStat(n.statSync(e),e,t)}},458:e=>{"use strict";e.exports=function(e){try{return e()}catch(e){}}},598:(e,t,r)=>{"use strict";var n=r(829);e.exports=function(e){var t=e.match(n);if(!t){return null}var r=t[0].replace(/#! ?/,"").split(" ");var o=r[0].split("/").pop();var s=r[1];return o==="env"?s:o+(s?" "+s:"")}},829:e=>{"use strict";e.exports=/^#!.*/},753:(e,t,r)=>{e.exports=which;which.sync=whichSync;var n=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys";var o=r(622);var s=n?";":":";var c=r(607);function getNotFoundError(e){var t=new Error("not found: "+e);t.code="ENOENT";return t}function getPathInfo(e,t){var r=t.colon||s;var o=t.path||process.env.PATH||"";var c=[""];o=o.split(r);var i="";if(n){o.unshift(process.cwd());i=t.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM";c=i.split(r);if(e.indexOf(".")!==-1&&c[0]!=="")c.unshift("")}if(e.match(/\//)||n&&e.match(/\\/))o=[""];return{env:o,ext:c,extExe:i}}function which(e,t,r){if(typeof t==="function"){r=t;t={}}var n=getPathInfo(e,t);var s=n.env;var i=n.ext;var a=n.extExe;var u=[];(function F(n,f){if(n===f){if(t.all&&u.length)return r(null,u);else return r(getNotFoundError(e))}var l=s[n];if(l.charAt(0)==='"'&&l.slice(-1)==='"')l=l.slice(1,-1);var p=o.join(l,e);if(!l&&/^\.[\\\/]/.test(e)){p=e.slice(0,2)+p}(function E(e,o){if(e===o)return F(n+1,f);var s=i[e];c(p+s,{pathExt:a},function(n,c){if(!n&&c){if(t.all)u.push(p+s);else return r(null,p+s)}return E(e+1,o)})})(0,i.length)})(0,s.length)}function whichSync(e,t){t=t||{};var r=getPathInfo(e,t);var n=r.env;var s=r.ext;var i=r.extExe;var a=[];for(var u=0,f=n.length;u<f;u++){var l=n[u];if(l.charAt(0)==='"'&&l.slice(-1)==='"')l=l.slice(1,-1);var p=o.join(l,e);if(!l&&/^\.[\\\/]/.test(e)){p=e.slice(0,2)+p}for(var m=0,h=s.length;m<h;m++){var v=p+s[m];var d;try{d=c.sync(v,{pathExt:i});if(d){if(t.all)a.push(v);else return v}}catch(e){}}}if(t.all&&a.length)return a;if(t.nothrow)return null;throw getNotFoundError(e)}},129:e=>{"use strict";e.exports=require("child_process")},747:e=>{"use strict";e.exports=require("fs")},519:e=>{"use strict";e.exports=require("next/dist/compiled/semver")},622:e=>{"use strict";e.exports=require("path")}};var t={};function __nccwpck_require__(r){if(t[r]){return t[r].exports}var n=t[r]={exports:{}};var o=true;try{e[r](n,n.exports,__nccwpck_require__);o=false}finally{if(o)delete t[r]}return n.exports}__nccwpck_require__.ab=__dirname+"/";return __nccwpck_require__(875)})();
\ No newline at end of file
{"name":"cross-spawn","main":"index.js","author":"André Cruz <andre@moxy.studio>","license":"MIT"}
...@@ -57,3 +57,23 @@ export const ESLINT_DEFAULT_DIRS = [ ...@@ -57,3 +57,23 @@ export const ESLINT_DEFAULT_DIRS = [
'src/components', 'src/components',
'src/lib', 'src/lib',
] ]
export const ESLINT_PROMPT_VALUES = [
{
title: 'Strict',
recommended: true,
config: {
extends: 'next/core-web-vitals',
},
},
{
title: 'Base',
config: {
extends: 'next',
},
},
{
title: 'Cancel',
config: null,
},
]
...@@ -126,9 +126,9 @@ export function formatResults( ...@@ -126,9 +126,9 @@ export function formatResults(
output: output:
resultsWithMessages.length > 0 resultsWithMessages.length > 0
? output + ? output +
`\n\n${chalk.bold( `\n\n${chalk.cyan(
'Need to disable some ESLint rules? Learn more here:' 'info'
)} https://nextjs.org/docs/basic-features/eslint#disabling-rules\n` )} - Need to disable some ESLint rules? Learn more here: https://nextjs.org/docs/basic-features/eslint#disabling-rules`
: '', : '',
totalNextPluginErrorCount, totalNextPluginErrorCount,
totalNextPluginWarningCount, totalNextPluginWarningCount,
......
import { promises as fs } from 'fs'
export type ConfigAvailable = {
exists: boolean
emptyEslintrc?: boolean
emptyPkgJsonConfig?: boolean
firstTimeSetup?: true
}
export async function hasEslintConfiguration(
eslintrcFile: string | null,
packageJsonConfig: { eslintConfig: any } | null
): Promise<ConfigAvailable> {
const configObject = {
exists: false,
emptyEslintrc: false,
emptyPkgJsonConfig: false,
}
if (eslintrcFile) {
const content = await fs.readFile(eslintrcFile, { encoding: 'utf8' }).then(
(txt) => txt.trim().replace(/\n/g, ''),
() => null
)
if (
content === '' ||
content === '{}' ||
content === '---' ||
content === 'module.exports = {}'
) {
return { ...configObject, emptyEslintrc: true }
}
} else if (packageJsonConfig?.eslintConfig) {
if (Object.entries(packageJsonConfig?.eslintConfig).length === 0) {
return {
...configObject,
emptyPkgJsonConfig: true,
}
}
} else {
return configObject
}
return { ...configObject, exists: true }
}
...@@ -8,11 +8,13 @@ import * as CommentJson from 'next/dist/compiled/comment-json' ...@@ -8,11 +8,13 @@ import * as CommentJson from 'next/dist/compiled/comment-json'
import { LintResult, formatResults } from './customFormatter' import { LintResult, formatResults } from './customFormatter'
import { writeDefaultConfig } from './writeDefaultConfig' import { writeDefaultConfig } from './writeDefaultConfig'
import { hasEslintConfiguration } from './hasEslintConfiguration'
import { ESLINT_PROMPT_VALUES } from '../constants'
import { existsSync, findPagesDir } from '../find-pages-dir' import { existsSync, findPagesDir } from '../find-pages-dir'
import { import { installDependencies } from '../install-dependencies'
hasNecessaryDependencies, import { hasNecessaryDependencies } from '../has-necessary-dependencies'
NecessaryDependencies, import { isYarn } from '../is-yarn'
} from '../has-necessary-dependencies'
import * as Log from '../../build/output/log' import * as Log from '../../build/output/log'
import { EventLintCheckCompleted } from '../../telemetry/events/build' import { EventLintCheckCompleted } from '../../telemetry/events/build'
...@@ -22,12 +24,50 @@ type Config = { ...@@ -22,12 +24,50 @@ type Config = {
rules: { [key: string]: Array<number | string> } rules: { [key: string]: Array<number | string> }
} }
const requiredPackages = [
{ file: 'eslint/lib/api.js', pkg: 'eslint' },
{ file: 'eslint-config-next', pkg: 'eslint-config-next' },
]
async function cliPrompt() {
console.log(
chalk.bold(
`${chalk.cyan(
'?'
)} How would you like to configure ESLint? https://nextjs.org/docs/basic-features/eslint`
)
)
try {
const cliSelect = (await import('next/dist/compiled/cli-select')).default
const { value } = await cliSelect({
values: ESLINT_PROMPT_VALUES,
valueRenderer: (
{
title,
recommended,
}: { title: string; recommended?: boolean; config: any },
selected: boolean
) => {
const name = selected ? chalk.bold.underline.cyan(title) : title
return name + (recommended ? chalk.bold.yellow(' (recommended)') : '')
},
selected: chalk.cyan('❯ '),
unselected: ' ',
})
return { config: value?.config }
} catch {
return { config: null }
}
}
async function lint( async function lint(
deps: NecessaryDependencies,
baseDir: string, baseDir: string,
lintDirs: string[], lintDirs: string[],
eslintrcFile: string | null, eslintrcFile: string | null,
pkgJsonPath: string | null, pkgJsonPath: string | null,
lintDuringBuild: boolean = false,
eslintOptions: any = null, eslintOptions: any = null,
reportErrorsOnly: boolean = false, reportErrorsOnly: boolean = false,
maxWarnings: number = -1, maxWarnings: number = -1,
...@@ -41,14 +81,27 @@ async function lint( ...@@ -41,14 +81,27 @@ async function lint(
eventInfo: EventLintCheckCompleted eventInfo: EventLintCheckCompleted
} }
> { > {
try {
// Load ESLint after we're sure it exists: // Load ESLint after we're sure it exists:
const deps = await hasNecessaryDependencies(baseDir, requiredPackages)
if (deps.missing.some((dep) => dep.pkg === 'eslint')) {
Log.error(
`ESLint must be installed${
lintDuringBuild ? ' in order to run during builds:' : ':'
} ${chalk.bold.cyan(
isYarn(baseDir)
? 'yarn add --dev eslint'
: 'npm install --save-dev eslint'
)}`
)
return null
}
const mod = await import(deps.resolved.get('eslint')!) const mod = await import(deps.resolved.get('eslint')!)
const { ESLint } = mod const { ESLint } = mod
let eslintVersion = ESLint?.version let eslintVersion = ESLint?.version ?? mod?.CLIEngine?.version
if (!ESLint) {
eslintVersion = mod?.CLIEngine?.version
if (!eslintVersion || semver.lt(eslintVersion, '7.0.0')) { if (!eslintVersion || semver.lt(eslintVersion, '7.0.0')) {
return `${chalk.red( return `${chalk.red(
...@@ -58,10 +111,6 @@ async function lint( ...@@ -58,10 +111,6 @@ async function lint(
}. Please upgrade to ESLint version 7 or later` }. Please upgrade to ESLint version 7 or later`
} }
return `${chalk.red(
'error'
)} - ESLint class not found. Please upgrade to ESLint version 7 or later`
}
let options: any = { let options: any = {
useEslintrc: true, useEslintrc: true,
baseConfig: {}, baseConfig: {},
...@@ -69,6 +118,7 @@ async function lint( ...@@ -69,6 +118,7 @@ async function lint(
extensions: ['.js', '.jsx', '.ts', '.tsx'], extensions: ['.js', '.jsx', '.ts', '.tsx'],
...eslintOptions, ...eslintOptions,
} }
let eslint = new ESLint(options) let eslint = new ESLint(options)
let nextEslintPluginIsEnabled = false let nextEslintPluginIsEnabled = false
...@@ -110,8 +160,14 @@ async function lint( ...@@ -110,8 +160,14 @@ async function lint(
if (updatedPagesDir) { if (updatedPagesDir) {
eslint = new ESLint(options) eslint = new ESLint(options)
} }
} else {
Log.warn(
'The Next.js plugin was not detected in your ESLint configuration. See https://nextjs.org/docs/basic-features/eslint#migrating-existing-config'
)
} }
const lintStart = process.hrtime() const lintStart = process.hrtime()
let results = await eslint.lintFiles(lintDirs) let results = await eslint.lintFiles(lintDirs)
let selectedFormatter = null let selectedFormatter = null
...@@ -151,6 +207,16 @@ async function lint( ...@@ -151,6 +207,16 @@ async function lint(
formattedResult.totalNextPluginWarningCount, formattedResult.totalNextPluginWarningCount,
}, },
} }
} catch (err) {
if (lintDuringBuild) {
Log.error(
`ESLint: ${err.message ? err.message.replace(/\n/g, ' ') : err}`
)
return null
} else {
throw new Error(err)
}
}
} }
export async function runLintCheck( export async function runLintCheck(
...@@ -160,7 +226,8 @@ export async function runLintCheck( ...@@ -160,7 +226,8 @@ export async function runLintCheck(
eslintOptions: any = null, eslintOptions: any = null,
reportErrorsOnly: boolean = false, reportErrorsOnly: boolean = false,
maxWarnings: number = -1, maxWarnings: number = -1,
formatter: string | null = null formatter: string | null = null,
strict: boolean = false
): ReturnType<typeof lint> { ): ReturnType<typeof lint> {
try { try {
// Find user's .eslintrc file // Find user's .eslintrc file
...@@ -187,45 +254,77 @@ export async function runLintCheck( ...@@ -187,45 +254,77 @@ export async function runLintCheck(
packageJsonConfig = CommentJson.parse(pkgJsonContent) packageJsonConfig = CommentJson.parse(pkgJsonContent)
} }
// Warning displayed if no ESLint configuration is present during build const config = await hasEslintConfiguration(eslintrcFile, packageJsonConfig)
if (lintDuringBuild && !eslintrcFile && !packageJsonConfig.eslintConfig) { let deps
if (config.exists) {
// Run if ESLint config exists
return await lint(
baseDir,
lintDirs,
eslintrcFile,
pkgJsonPath,
lintDuringBuild,
eslintOptions,
reportErrorsOnly,
maxWarnings,
formatter
)
} else {
// Display warning if no ESLint configuration is present during "next build"
if (lintDuringBuild) {
Log.warn( Log.warn(
`No ESLint configuration detected. Run ${chalk.bold.cyan( `No ESLint configuration detected. Run ${chalk.bold.cyan(
'next lint' 'next lint'
)} to begin setup` )} to begin setup`
) )
return null return null
} } else {
// Ask user what config they would like to start with for first time "next lint" setup
const { config: selectedConfig } = strict
? ESLINT_PROMPT_VALUES.find(
(opt: { title: string }) => opt.title === 'Strict'
)!
: await cliPrompt()
// Ensure ESLint and necessary plugins and configs are installed: if (selectedConfig == null) {
const deps: NecessaryDependencies = await hasNecessaryDependencies( // Show a warning if no option is selected in prompt
baseDir, Log.warn(
false, 'If you set up ESLint yourself, we recommend adding the Next.js ESLint plugin. See https://nextjs.org/docs/basic-features/eslint#migrating-existing-config'
true,
lintDuringBuild
) )
return null
} else {
// Check if necessary deps installed, and install any that are missing
deps = await hasNecessaryDependencies(baseDir, requiredPackages)
if (deps.missing.length > 0)
await installDependencies(baseDir, deps.missing, true)
// Write default ESLint config if none is present // Write default ESLint config.
// Check for /pages and src/pages is to make sure this happens in Next.js folder // Check for /pages and src/pages is to make sure this happens in Next.js folder
if ( if (
existsSync(path.join(baseDir, 'pages')) || existsSync(path.join(baseDir, 'pages')) ||
existsSync(path.join(baseDir, 'src/pages')) existsSync(path.join(baseDir, 'src/pages'))
) { ) {
await writeDefaultConfig(eslintrcFile, pkgJsonPath, packageJsonConfig) await writeDefaultConfig(
}
// Run ESLint
return await lint(
deps,
baseDir, baseDir,
lintDirs, config,
selectedConfig,
eslintrcFile, eslintrcFile,
pkgJsonPath, pkgJsonPath,
eslintOptions, packageJsonConfig
reportErrorsOnly, )
maxWarnings, }
formatter }
Log.ready(
`ESLint has successfully been configured. Run ${chalk.bold.cyan(
'next lint'
)} again to view warnings and errors.`
) )
return null
}
}
} catch (err) { } catch (err) {
throw err throw err
} }
......
...@@ -2,37 +2,27 @@ import { promises as fs } from 'fs' ...@@ -2,37 +2,27 @@ import { promises as fs } from 'fs'
import chalk from 'chalk' import chalk from 'chalk'
import os from 'os' import os from 'os'
import path from 'path' import path from 'path'
import * as CommentJson from 'next/dist/compiled/comment-json' import * as CommentJson from 'next/dist/compiled/comment-json'
import { ConfigAvailable } from './hasEslintConfiguration'
import * as Log from '../../build/output/log'
export async function writeDefaultConfig( export async function writeDefaultConfig(
baseDir: string,
{ exists, emptyEslintrc, emptyPkgJsonConfig }: ConfigAvailable,
selectedConfig: any,
eslintrcFile: string | null, eslintrcFile: string | null,
pkgJsonPath: string | null, pkgJsonPath: string | null,
packageJsonConfig: { eslintConfig: any } | null packageJsonConfig: { eslintConfig: any } | null
) { ) {
const defaultConfig = { if (!exists && emptyEslintrc && eslintrcFile) {
extends: 'next',
}
if (eslintrcFile) {
const content = await fs.readFile(eslintrcFile, { encoding: 'utf8' }).then(
(txt) => txt.trim().replace(/\n/g, ''),
() => null
)
if (
content === '' ||
content === '{}' ||
content === '---' ||
content === 'module.exports = {}'
) {
const ext = path.extname(eslintrcFile) const ext = path.extname(eslintrcFile)
let newFileContent let newFileContent
if (ext === '.yaml' || ext === '.yml') { if (ext === '.yaml' || ext === '.yml') {
newFileContent = "extends: 'next'" newFileContent = "extends: 'next'"
} else { } else {
newFileContent = CommentJson.stringify(defaultConfig, null, 2) newFileContent = CommentJson.stringify(selectedConfig, null, 2)
if (ext === '.js') { if (ext === '.js') {
newFileContent = 'module.exports = ' + newFileContent newFileContent = 'module.exports = ' + newFileContent
...@@ -41,18 +31,13 @@ export async function writeDefaultConfig( ...@@ -41,18 +31,13 @@ export async function writeDefaultConfig(
await fs.writeFile(eslintrcFile, newFileContent + os.EOL) await fs.writeFile(eslintrcFile, newFileContent + os.EOL)
console.log( Log.info(
chalk.green(
`We detected an empty ESLint configuration file (${chalk.bold( `We detected an empty ESLint configuration file (${chalk.bold(
path.basename(eslintrcFile) path.basename(eslintrcFile)
)}) and updated it for you to include the base Next.js ESLint configuration.` )}) and updated it for you!`
) )
) } else if (!exists && emptyPkgJsonConfig && packageJsonConfig) {
} packageJsonConfig.eslintConfig = selectedConfig
} else if (packageJsonConfig?.eslintConfig) {
// Creates .eslintrc only if package.json's eslintConfig field is empty
if (Object.entries(packageJsonConfig?.eslintConfig).length === 0) {
packageJsonConfig.eslintConfig = defaultConfig
if (pkgJsonPath) if (pkgJsonPath)
await fs.writeFile( await fs.writeFile(
...@@ -60,25 +45,22 @@ export async function writeDefaultConfig( ...@@ -60,25 +45,22 @@ export async function writeDefaultConfig(
CommentJson.stringify(packageJsonConfig, null, 2) + os.EOL CommentJson.stringify(packageJsonConfig, null, 2) + os.EOL
) )
console.log( Log.info(
chalk.green(
`We detected an empty ${chalk.bold( `We detected an empty ${chalk.bold(
'eslintConfig' 'eslintConfig'
)} field in package.json and updated it for you to include the base Next.js ESLint configuration.` )} field in package.json and updated it for you!`
) )
) } else if (!exists) {
}
} else {
await fs.writeFile( await fs.writeFile(
'.eslintrc.json', path.join(baseDir, '.eslintrc.json'),
CommentJson.stringify(defaultConfig, null, 2) + os.EOL CommentJson.stringify(selectedConfig, null, 2) + os.EOL
) )
console.log( console.log(
chalk.green( chalk.green(
`We created the ${chalk.bold( `We created the ${chalk.bold(
'.eslintrc.json' '.eslintrc.json'
)} file for you and included the base Next.js ESLint configuration.` )} file for you and included your selected configuration.`
) )
) )
} }
......
import chalk from 'chalk' export interface MissingDependency {
import { join } from 'path' file: string
pkg: string
import { fileExists } from './file-exists' }
import { getOxfordCommaList } from './oxford-comma-list'
import { FatalError } from './fatal-error'
const requiredTSPackages = [
{ file: 'typescript', pkg: 'typescript' },
{ file: '@types/react/index.d.ts', pkg: '@types/react' },
{ file: '@types/node/index.d.ts', pkg: '@types/node' },
]
const requiredLintPackages = [
{ file: 'eslint/lib/api.js', pkg: 'eslint' },
{ file: 'eslint-config-next', pkg: 'eslint-config-next' },
]
export type NecessaryDependencies = { export type NecessaryDependencies = {
resolved: Map<string, string> resolved: Map<string, string>
missing: MissingDependency[]
} }
export async function hasNecessaryDependencies( export async function hasNecessaryDependencies(
baseDir: string, baseDir: string,
checkTSDeps: boolean, requiredPackages: MissingDependency[]
checkESLintDeps: boolean,
lintDuringBuild: boolean = false
): Promise<NecessaryDependencies> { ): Promise<NecessaryDependencies> {
if (!checkTSDeps && !checkESLintDeps) {
return { resolved: undefined! }
}
let resolutions = new Map<string, string>() let resolutions = new Map<string, string>()
let requiredPackages = checkESLintDeps
? requiredLintPackages
: requiredTSPackages
const missingPackages = requiredPackages.filter((p) => { const missingPackages = requiredPackages.filter((p) => {
try { try {
resolutions.set(p.pkg, require.resolve(p.file, { paths: [baseDir] })) resolutions.set(p.pkg, require.resolve(p.file, { paths: [baseDir] }))
...@@ -44,47 +22,8 @@ export async function hasNecessaryDependencies( ...@@ -44,47 +22,8 @@ export async function hasNecessaryDependencies(
} }
}) })
if (missingPackages.length < 1) {
return { return {
resolved: resolutions, resolved: resolutions,
missing: missingPackages,
} }
}
const packagesHuman = getOxfordCommaList(missingPackages.map((p) => p.pkg))
const packagesCli = missingPackages.map((p) => p.pkg).join(' ')
const yarnLockFile = join(baseDir, 'yarn.lock')
const isYarn = await fileExists(yarnLockFile).catch(() => false)
const removalTSMsg =
'\n\n' +
chalk.bold(
'If you are not trying to use TypeScript, please remove the ' +
chalk.cyan('tsconfig.json') +
' file from your package root (and any TypeScript files in your pages directory).'
)
const removalLintMsg =
`\n\n` +
(lintDuringBuild
? `If you do not want to run ESLint during builds, disable it in next.config.js. See https://nextjs.org/docs/api-reference/next.config.js/ignoring-eslint`
: `Once installed, run ${chalk.bold.cyan('next lint')} again.`)
const removalMsg = checkTSDeps ? removalTSMsg : removalLintMsg
throw new FatalError(
chalk.bold.red(
checkTSDeps
? `It looks like you're trying to use TypeScript but do not have the required package(s) installed.`
: `To use ESLint, additional required package(s) must be installed.`
) +
'\n\n' +
chalk.bold(`Please install ${chalk.bold(packagesHuman)} by running:`) +
'\n\n' +
`\t${chalk.bold.cyan(
(isYarn ? 'yarn add --dev' : 'npm install --save-dev') +
' ' +
packagesCli
)}` +
removalMsg +
'\n'
)
} }
import { execSync } from 'child_process'
import dns from 'dns'
import url from 'url'
function getProxy(): string | undefined {
if (process.env.https_proxy) {
return process.env.https_proxy
}
try {
const httpsProxy = execSync('npm config get https-proxy').toString().trim()
return httpsProxy !== 'null' ? httpsProxy : undefined
} catch (e) {
return
}
}
export function getOnline(): Promise<boolean> {
return new Promise((resolve) => {
dns.lookup('registry.yarnpkg.com', (registryErr) => {
if (!registryErr) {
return resolve(true)
}
const proxy = getProxy()
if (!proxy) {
return resolve(false)
}
const { hostname } = url.parse(proxy)
if (!hostname) {
return resolve(false)
}
dns.lookup(hostname, (proxyErr) => {
resolve(proxyErr == null)
})
})
})
}
/* eslint-disable import/no-extraneous-dependencies */
import chalk from 'chalk'
import spawn from 'next/dist/compiled/cross-spawn'
interface InstallArgs {
/**
* Indicate whether to install packages using Yarn.
*/
useYarn: boolean
/**
* Indicate whether there is an active Internet connection.
*/
isOnline: boolean
/**
* Indicate whether the given dependencies are devDependencies.
*/
devDependencies?: boolean
}
/**
* Spawn a package manager installation with either Yarn or NPM.
*
* @returns A Promise that resolves once the installation is finished.
*/
export function install(
root: string,
dependencies: string[] | null,
{ useYarn, isOnline, devDependencies }: InstallArgs
): Promise<void> {
/**
* NPM-specific command-line flags.
*/
const npmFlags: string[] = []
/**
* Yarn-specific command-line flags.
*/
const yarnFlags: string[] = []
/**
* Return a Promise that resolves once the installation is finished.
*/
return new Promise((resolve, reject) => {
let args: string[]
let command: string = useYarn ? 'yarnpkg' : 'npm'
if (dependencies && dependencies.length) {
/**
* If there are dependencies, run a variation of `{displayCommand} add`.
*/
if (useYarn) {
/**
* Call `yarn add --exact (--offline)? (-D)? ...`.
*/
args = ['add', '--exact']
if (!isOnline) args.push('--offline')
args.push('--cwd', root)
if (devDependencies) args.push('--dev')
args.push(...dependencies)
} else {
/**
* Call `npm install [--save|--save-dev] ...`.
*/
args = ['install', '--save-exact']
args.push(devDependencies ? '--save-dev' : '--save')
args.push(...dependencies)
}
} else {
/**
* If there are no dependencies, run a variation of `{displayCommand}
* install`.
*/
args = ['install']
if (useYarn) {
if (!isOnline) {
console.log(chalk.yellow('You appear to be offline.'))
console.log(chalk.yellow('Falling back to the local Yarn cache.'))
console.log()
args.push('--offline')
}
} else {
if (!isOnline) {
console.log(chalk.yellow('You appear to be offline.'))
console.log()
}
}
}
/**
* Add any package manager-specific flags.
*/
if (useYarn) {
args.push(...yarnFlags)
} else {
args.push(...npmFlags)
}
/**
* Spawn the installation process.
*/
const child = spawn(command, args, {
stdio: 'inherit',
env: {
...process.env,
NODE_ENV: devDependencies ? 'development' : 'production',
ADBLOCK: '1',
DISABLE_OPENCOLLECTIVE: '1',
},
})
child.on('close', (code) => {
if (code !== 0) {
reject({ command: `${command} ${args.join(' ')}` })
return
}
resolve()
})
})
}
import { execSync } from 'child_process'
export function shouldUseYarn(): boolean {
try {
const userAgent = process.env.npm_config_user_agent
if (userAgent) {
return Boolean(userAgent && userAgent.startsWith('yarn'))
}
execSync('yarnpkg --version', { stdio: 'ignore' })
return true
} catch (e) {
return false
}
}
import chalk from 'chalk'
import path from 'path'
import { MissingDependency } from './has-necessary-dependencies'
import { shouldUseYarn } from './helpers/should-use-yarn'
import { install } from './helpers/install'
import { getOnline } from './helpers/get-online'
export type Dependencies = {
resolved: Map<string, string>
}
export async function installDependencies(
baseDir: string,
deps: any,
dev: boolean = false
) {
const useYarn = shouldUseYarn()
const isOnline = !useYarn || (await getOnline())
if (deps.length) {
console.log()
console.log(`Installing ${dev ? 'devDependencies' : 'dependencies'}:`)
for (const dep of deps) {
console.log(`- ${chalk.cyan(dep.pkg)}`)
}
console.log()
const devInstallFlags = { devDependencies: dev, ...{ useYarn, isOnline } }
await install(
path.resolve(baseDir),
deps.map((dep: MissingDependency) => dep.pkg),
devInstallFlags
)
console.log()
}
}
import { join } from 'path'
import { fileExists } from './file-exists'
export const isYarn = async (dir: string) =>
await fileExists(join(dir, 'yarn.lock')).catch(() => false)
import chalk from 'chalk'
import { getOxfordCommaList } from '../oxford-comma-list'
import { MissingDependency } from '../has-necessary-dependencies'
import { FatalError } from '../fatal-error'
import { isYarn } from '../is-yarn'
export function missingDepsError(
dir: string,
missingPackages: MissingDependency[]
) {
const packagesHuman = getOxfordCommaList(missingPackages.map((p) => p.pkg))
const packagesCli = missingPackages.map((p) => p.pkg).join(' ')
const removalMsg =
'\n\n' +
chalk.bold(
'If you are not trying to use TypeScript, please remove the ' +
chalk.cyan('tsconfig.json') +
' file from your package root (and any TypeScript files in your pages directory).'
)
throw new FatalError(
chalk.bold.red(
`It looks like you're trying to use TypeScript but do not have the required package(s) installed.`
) +
'\n\n' +
chalk.bold(`Please install ${chalk.bold(packagesHuman)} by running:`) +
'\n\n' +
`\t${chalk.bold.cyan(
(isYarn(dir) ? 'yarn add --dev' : 'npm install --save-dev') +
' ' +
packagesCli
)}` +
removalMsg +
'\n'
)
}
...@@ -13,6 +13,13 @@ import { getTypeScriptIntent } from './typescript/getTypeScriptIntent' ...@@ -13,6 +13,13 @@ import { getTypeScriptIntent } from './typescript/getTypeScriptIntent'
import { TypeCheckResult } from './typescript/runTypeCheck' import { TypeCheckResult } from './typescript/runTypeCheck'
import { writeAppTypeDeclarations } from './typescript/writeAppTypeDeclarations' import { writeAppTypeDeclarations } from './typescript/writeAppTypeDeclarations'
import { writeConfigurationDefaults } from './typescript/writeConfigurationDefaults' import { writeConfigurationDefaults } from './typescript/writeConfigurationDefaults'
import { missingDepsError } from './typescript/missingDependencyError'
const requiredPackages = [
{ file: 'typescript', pkg: 'typescript' },
{ file: '@types/react/index.d.ts', pkg: '@types/react' },
{ file: '@types/node/index.d.ts', pkg: '@types/node' },
]
export async function verifyTypeScriptSetup( export async function verifyTypeScriptSetup(
dir: string, dir: string,
...@@ -29,15 +36,17 @@ export async function verifyTypeScriptSetup( ...@@ -29,15 +36,17 @@ export async function verifyTypeScriptSetup(
if (!intent) { if (!intent) {
return { version: null } return { version: null }
} }
const firstTimeSetup = intent.firstTimeSetup
// Ensure TypeScript and necessary `@types/*` are installed: // Ensure TypeScript and necessary `@types/*` are installed:
const deps: NecessaryDependencies = await hasNecessaryDependencies( const deps: NecessaryDependencies = await hasNecessaryDependencies(
dir, dir,
!!intent, requiredPackages
false
) )
if (deps.missing?.length > 0) {
missingDepsError(dir, deps.missing)
}
// Load TypeScript after we're sure it exists: // Load TypeScript after we're sure it exists:
const ts = (await import( const ts = (await import(
deps.resolved.get('typescript')! deps.resolved.get('typescript')!
...@@ -50,7 +59,7 @@ export async function verifyTypeScriptSetup( ...@@ -50,7 +59,7 @@ export async function verifyTypeScriptSetup(
} }
// Reconfigure (or create) the user's `tsconfig.json` for them: // Reconfigure (or create) the user's `tsconfig.json` for them:
await writeConfigurationDefaults(ts, tsConfigPath, firstTimeSetup) await writeConfigurationDefaults(ts, tsConfigPath, intent.firstTimeSetup)
// Write out the necessary `next-env.d.ts` file to correctly register // Write out the necessary `next-env.d.ts` file to correctly register
// Next.js' types: // Next.js' types:
await writeAppTypeDeclarations(dir, imageImportsEnabled) await writeAppTypeDeclarations(dir, imageImportsEnabled)
......
...@@ -196,11 +196,13 @@ ...@@ -196,11 +196,13 @@
"bfj": "7.0.2", "bfj": "7.0.2",
"cacache": "15.0.5", "cacache": "15.0.5",
"ci-info": "watson/ci-info#f43f6a1cefff47fb361c88cf4b943fdbcaafe540", "ci-info": "watson/ci-info#f43f6a1cefff47fb361c88cf4b943fdbcaafe540",
"cli-select": "1.1.2",
"comment-json": "3.0.3", "comment-json": "3.0.3",
"compression": "1.7.4", "compression": "1.7.4",
"conf": "5.0.0", "conf": "5.0.0",
"content-type": "1.0.4", "content-type": "1.0.4",
"cookie": "0.4.1", "cookie": "0.4.1",
"cross-spawn": "6.0.5",
"css-loader": "4.3.0", "css-loader": "4.3.0",
"debug": "4.1.1", "debug": "4.1.1",
"devalue": "2.0.1", "devalue": "2.0.1",
......
...@@ -196,6 +196,14 @@ export async function ncc_ci_info(task, opts) { ...@@ -196,6 +196,14 @@ export async function ncc_ci_info(task, opts) {
.ncc({ packageName: 'ci-info', externals }) .ncc({ packageName: 'ci-info', externals })
.target('compiled/ci-info') .target('compiled/ci-info')
} }
// eslint-disable-next-line camelcase
externals['cli-select'] = 'next/dist/compiled/cli-select'
export async function ncc_cli_select(task, opts) {
await task
.source(opts.src || relative(__dirname, require.resolve('cli-select')))
.ncc({ packageName: 'cli-select', externals })
.target('compiled/cli-select')
}
externals['comment-json'] = 'next/dist/compiled/comment-json' externals['comment-json'] = 'next/dist/compiled/comment-json'
export async function ncc_comment_json(task, opts) { export async function ncc_comment_json(task, opts) {
await task await task
...@@ -236,6 +244,14 @@ export async function ncc_cookie(task, opts) { ...@@ -236,6 +244,14 @@ export async function ncc_cookie(task, opts) {
.target('compiled/cookie') .target('compiled/cookie')
} }
// eslint-disable-next-line camelcase // eslint-disable-next-line camelcase
externals['cross-spawn'] = 'next/dist/compiled/cross-spawn'
export async function ncc_cross_spawn(task, opts) {
await task
.source(opts.src || relative(__dirname, require.resolve('cross-spawn')))
.ncc({ packageName: 'cross-spawn', externals })
.target('compiled/cross-spawn')
}
// eslint-disable-next-line camelcase
externals['css-loader'] = 'next/dist/compiled/css-loader' externals['css-loader'] = 'next/dist/compiled/css-loader'
export async function ncc_css_loader(task, opts) { export async function ncc_css_loader(task, opts) {
await task await task
...@@ -740,11 +756,13 @@ export async function ncc(task, opts) { ...@@ -740,11 +756,13 @@ export async function ncc(task, opts) {
'ncc_bfj', 'ncc_bfj',
'ncc_cacache', 'ncc_cacache',
'ncc_ci_info', 'ncc_ci_info',
'ncc_cli_select',
'ncc_comment_json', 'ncc_comment_json',
'ncc_compression', 'ncc_compression',
'ncc_conf', 'ncc_conf',
'ncc_content_type', 'ncc_content_type',
'ncc_cookie', 'ncc_cookie',
'ncc_cross_spawn',
'ncc_css_loader', 'ncc_css_loader',
'ncc_debug', 'ncc_debug',
'ncc_devalue', 'ncc_devalue',
......
...@@ -75,6 +75,10 @@ declare module 'next/dist/compiled/ci-info' { ...@@ -75,6 +75,10 @@ declare module 'next/dist/compiled/ci-info' {
import m from 'ci-info' import m from 'ci-info'
export = m export = m
} }
declare module 'next/dist/compiled/cli-select' {
import m from 'cli-select'
export = m
}
declare module 'next/dist/compiled/compression' { declare module 'next/dist/compiled/compression' {
import m from 'compression' import m from 'compression'
export = m export = m
...@@ -91,6 +95,10 @@ declare module 'next/dist/compiled/cookie' { ...@@ -91,6 +95,10 @@ declare module 'next/dist/compiled/cookie' {
import m from 'cookie' import m from 'cookie'
export = m export = m
} }
declare module 'next/dist/compiled/cross-spawn' {
import m from 'cross-spawn'
export = m
}
declare module 'next/dist/compiled/debug' { declare module 'next/dist/compiled/debug' {
import m from 'debug' import m from 'debug'
export = m export = m
......
...@@ -53,7 +53,7 @@ describe('create next app', () => { ...@@ -53,7 +53,7 @@ describe('create next app', () => {
fs.existsSync(path.join(cwd, projectName, 'pages/index.js')) fs.existsSync(path.join(cwd, projectName, 'pages/index.js'))
).toBeTruthy() ).toBeTruthy()
expect( expect(
fs.existsSync(path.join(cwd, projectName, '.eslintrc')) fs.existsSync(path.join(cwd, projectName, '.eslintrc.json'))
).toBeTruthy() ).toBeTruthy()
expect( expect(
fs.existsSync(path.join(cwd, projectName, 'node_modules/next')) fs.existsSync(path.join(cwd, projectName, 'node_modules/next'))
...@@ -125,7 +125,7 @@ describe('create next app', () => { ...@@ -125,7 +125,7 @@ describe('create next app', () => {
fs.existsSync(path.join(cwd, projectName, 'next-env.d.ts')) fs.existsSync(path.join(cwd, projectName, 'next-env.d.ts'))
).toBeTruthy() ).toBeTruthy()
expect( expect(
fs.existsSync(path.join(cwd, projectName, '.eslintrc')) fs.existsSync(path.join(cwd, projectName, '.eslintrc.json'))
).toBeTruthy() ).toBeTruthy()
expect( expect(
fs.existsSync(path.join(cwd, projectName, 'node_modules/next')) fs.existsSync(path.join(cwd, projectName, 'node_modules/next'))
...@@ -254,7 +254,7 @@ describe('create next app', () => { ...@@ -254,7 +254,7 @@ describe('create next app', () => {
'package.json', 'package.json',
'pages/index.js', 'pages/index.js',
'.gitignore', '.gitignore',
'.eslintrc', '.eslintrc.json',
] ]
files.forEach((file) => files.forEach((file) =>
expect(fs.existsSync(path.join(cwd, projectName, file))).toBeTruthy() expect(fs.existsSync(path.join(cwd, projectName, file))).toBeTruthy()
...@@ -322,7 +322,7 @@ describe('create next app', () => { ...@@ -322,7 +322,7 @@ describe('create next app', () => {
'pages/index.js', 'pages/index.js',
'.gitignore', '.gitignore',
'node_modules/next', 'node_modules/next',
'.eslintrc', '.eslintrc.json',
] ]
files.forEach((file) => files.forEach((file) =>
expect(fs.existsSync(path.join(cwd, file))).toBeTruthy() expect(fs.existsSync(path.join(cwd, file))).toBeTruthy()
...@@ -341,7 +341,7 @@ describe('create next app', () => { ...@@ -341,7 +341,7 @@ describe('create next app', () => {
'pages/index.js', 'pages/index.js',
'.gitignore', '.gitignore',
'node_modules/next', 'node_modules/next',
'.eslintrc', '.eslintrc.json',
] ]
files.forEach((file) => files.forEach((file) =>
expect(fs.existsSync(path.join(cwd, projectName, file))).toBeTruthy() expect(fs.existsSync(path.join(cwd, projectName, file))).toBeTruthy()
...@@ -359,7 +359,7 @@ describe('create next app', () => { ...@@ -359,7 +359,7 @@ describe('create next app', () => {
'package.json', 'package.json',
'pages/index.js', 'pages/index.js',
'.gitignore', '.gitignore',
'.eslintrc', '.eslintrc.json',
'package-lock.json', 'package-lock.json',
'node_modules/next', 'node_modules/next',
] ]
......
...@@ -56,7 +56,10 @@ describe('distDir', () => { ...@@ -56,7 +56,10 @@ describe('distDir', () => {
it('should handle null/undefined distDir', async () => { it('should handle null/undefined distDir', async () => {
const origNextConfig = await fs.readFile(nextConfig, 'utf8') const origNextConfig = await fs.readFile(nextConfig, 'utf8')
await fs.writeFile(nextConfig, `module.exports = { distDir: null }`) await fs.writeFile(
nextConfig,
`module.exports = { distDir: null, eslint: { ignoreDuringBuilds: true } }`
)
const { stderr } = await nextBuild(appDir, [], { stderr: true }) const { stderr } = await nextBuild(appDir, [], { stderr: true })
await fs.writeFile(nextConfig, origNextConfig) await fs.writeFile(nextConfig, origNextConfig)
......
export default class Test {
render() {
return (
<div>
<h1>Hello title</h1>
</div>
)
}
}
{ {
"root": true, "root": true,
"extends": "next" "extends": "eslint:recommended"
} }
const Home = () => (
<div>
<p>Home</p>
</div>
)
export default Home
import fs from 'fs-extra' import fs from 'fs-extra'
import { join } from 'path' import os from 'os'
import execa from 'execa'
import { dirname, join } from 'path'
import findUp from 'next/dist/compiled/find-up' import findUp from 'next/dist/compiled/find-up'
import { nextBuild, nextLint } from 'next-test-utils' import { nextBuild, nextLint } from 'next-test-utils'
import { writeFile, readFile } from 'fs-extra'
jest.setTimeout(1000 * 60 * 2) jest.setTimeout(1000 * 60 * 2)
...@@ -24,25 +27,23 @@ const dirInvalidEslintVersion = join(__dirname, '../invalid-eslint-version') ...@@ -24,25 +27,23 @@ const dirInvalidEslintVersion = join(__dirname, '../invalid-eslint-version')
const dirMaxWarnings = join(__dirname, '../max-warnings') const dirMaxWarnings = join(__dirname, '../max-warnings')
const dirEmptyDirectory = join(__dirname, '../empty-directory') const dirEmptyDirectory = join(__dirname, '../empty-directory')
const dirEslintIgnore = join(__dirname, '../eslint-ignore') const dirEslintIgnore = join(__dirname, '../eslint-ignore')
const dirNoEslintPlugin = join(__dirname, '../no-eslint-plugin')
const dirNoConfig = join(__dirname, '../no-config')
describe('ESLint', () => { describe('ESLint', () => {
describe('Next Build', () => { describe('Next Build', () => {
test('first time setup', async () => { test('first time setup', async () => {
const eslintrc = join(dirFirstTimeSetup, '.eslintrc') const eslintrcJson = join(dirFirstTimeSetup, '.eslintrc.json')
await writeFile(eslintrc, '') await fs.writeFile(eslintrcJson, '')
const { stdout, stderr } = await nextBuild(dirFirstTimeSetup, [], { const { stdout, stderr } = await nextBuild(dirFirstTimeSetup, [], {
stdout: true, stdout: true,
stderr: true, stderr: true,
}) })
const output = stdout + stderr const output = stdout + stderr
const eslintrcContent = await readFile(eslintrc, 'utf8')
expect(output).toContain( expect(output).toContain(
'We detected an empty ESLint configuration file (.eslintrc) and updated it for you to include the base Next.js ESLint configuration.' 'No ESLint configuration detected. Run next lint to begin setup'
)
expect(eslintrcContent.trim().replace(/\s/g, '')).toMatch(
'{"extends":"next"}'
) )
}) })
...@@ -131,27 +132,98 @@ describe('ESLint', () => { ...@@ -131,27 +132,98 @@ describe('ESLint', () => {
) )
expect(output).toContain('Compiled successfully') expect(output).toContain('Compiled successfully')
}) })
test('missing Next.js plugin', async () => {
const { stdout, stderr } = await nextBuild(dirNoEslintPlugin, [], {
stdout: true,
stderr: true,
})
const output = stdout + stderr
expect(output).toContain(
'The Next.js plugin was not detected in your ESLint configuration'
)
})
}) })
describe('Next Lint', () => { describe('Next Lint', () => {
test('first time setup', async () => { describe('First Time Setup ', () => {
const eslintrc = join(dirFirstTimeSetup, '.eslintrc') async function nextLintTemp() {
await writeFile(eslintrc, '') const folder = join(
os.tmpdir(),
Math.random().toString(36).substring(2)
)
await fs.mkdirp(folder)
await fs.copy(dirNoConfig, folder)
try {
const nextDir = dirname(require.resolve('next/package'))
const nextBin = join(nextDir, 'dist/bin/next')
const { stdout } = await execa('node', [
nextBin,
'lint',
folder,
'--strict',
])
const pkgJson = JSON.parse(
await fs.readFile(join(folder, 'package.json'), 'utf8')
)
const eslintrcJson = JSON.parse(
await fs.readFile(join(folder, '.eslintrc.json'), 'utf8')
)
return { stdout, pkgJson, eslintrcJson }
} finally {
await fs.remove(folder)
}
}
test('show a prompt to set up ESLint if no configuration detected', async () => {
const eslintrcJson = join(dirFirstTimeSetup, '.eslintrc.json')
await fs.writeFile(eslintrcJson, '')
const { stdout, stderr } = await nextLint(dirFirstTimeSetup, [], { const { stdout, stderr } = await nextLint(dirFirstTimeSetup, [], {
stdout: true, stdout: true,
stderr: true, stderr: true,
}) })
const output = stdout + stderr const output = stdout + stderr
const eslintrcContent = await readFile(eslintrc, 'utf8') expect(output).toContain('How would you like to configure ESLint?')
expect(output).toContain( // Different options that can be selected
'We detected an empty ESLint configuration file (.eslintrc) and updated it for you to include the base Next.js ESLint configuration.' expect(output).toContain('Strict (recommended)')
expect(output).toContain('Base')
expect(output).toContain('Cancel')
})
test('installs eslint and eslint-config-next as devDependencies if missing', async () => {
const { stdout, pkgJson } = await nextLintTemp()
expect(stdout.replace(/(\r\n|\n|\r)/gm, '')).toContain(
'Installing devDependencies:- eslint- eslint-config-next'
)
expect(pkgJson.devDependencies).toHaveProperty('eslint')
expect(pkgJson.devDependencies).toHaveProperty('eslint-config-next')
})
test('creates .eslintrc.json file with a default configuration', async () => {
const { stdout, eslintrcJson } = await nextLintTemp()
expect(stdout).toContain(
'We created the .eslintrc.json file for you and included your selected configuration'
) )
expect(eslintrcContent.trim().replace(/\s/g, '')).toMatch( expect(eslintrcJson).toMatchObject({ extends: 'next/core-web-vitals' })
'{"extends":"next"}' })
test('shows a successful message when completed', async () => {
const { stdout, eslintrcJson } = await nextLintTemp()
expect(stdout).toContain(
'ESLint has successfully been configured. Run next lint again to view warnings and errors'
) )
}) })
})
test('shows warnings and errors', async () => { test('shows warnings and errors', async () => {
const { stdout, stderr } = await nextLint(dirCustomConfig, [], { const { stdout, stderr } = await nextLint(dirCustomConfig, [], {
...@@ -222,6 +294,9 @@ describe('ESLint', () => { ...@@ -222,6 +294,9 @@ describe('ESLint', () => {
}) })
test('success message when no warnings or errors', async () => { test('success message when no warnings or errors', async () => {
const eslintrcJson = join(dirFirstTimeSetup, '.eslintrc.json')
await fs.writeFile(eslintrcJson, '{ "extends": "next", "root": true }')
const { stdout, stderr } = await nextLint(dirFirstTimeSetup, [], { const { stdout, stderr } = await nextLint(dirFirstTimeSetup, [], {
stdout: true, stdout: true,
stderr: true, stderr: true,
...@@ -259,7 +334,7 @@ describe('ESLint', () => { ...@@ -259,7 +334,7 @@ describe('ESLint', () => {
const output = stdout + stderr const output = stdout + stderr
expect(output).not.toContain( expect(output).not.toContain(
'We created the .eslintrc file for you and included the base Next.js ESLint configuration' 'We created the .eslintrc file for you and included your selected configuration'
) )
} finally { } finally {
// Restore original .eslintrc file // Restore original .eslintrc file
......
module.exports = { module.exports = {
eslint: {
ignoreDuringBuilds: true,
},
webpack(config, options) { webpack(config, options) {
config.module.rules.push({ config.module.rules.push({
test: /\.svg$/, test: /\.svg$/,
......
module.exports = {
eslint: {
ignoreDuringBuilds: true,
},
}
module.exports = { module.exports = {
eslint: {
ignoreDuringBuilds: true,
},
webpack(config) { webpack(config) {
console.log('Initialized config') console.log('Initialized config')
if ( if (
......
...@@ -5134,7 +5134,7 @@ ansi-colors@^4.1.1: ...@@ -5134,7 +5134,7 @@ ansi-colors@^4.1.1:
resolved "https://registry.yarnpkg.com/ansi-colors/-/ansi-colors-4.1.1.tgz#cbb9ae256bf750af1eab344f229aa27fe94ba348" resolved "https://registry.yarnpkg.com/ansi-colors/-/ansi-colors-4.1.1.tgz#cbb9ae256bf750af1eab344f229aa27fe94ba348"
integrity sha512-JoX0apGbHaUJBNl6yF+p6JAFYZ666/hhCGKN5t9QFjbJQKUU/g8MNbFDbvfrgKXvI1QpZplPOnwIo99lX/AAmA== integrity sha512-JoX0apGbHaUJBNl6yF+p6JAFYZ666/hhCGKN5t9QFjbJQKUU/g8MNbFDbvfrgKXvI1QpZplPOnwIo99lX/AAmA==
ansi-escapes@^3.0.0: ansi-escapes@^3.0.0, ansi-escapes@^3.2.0:
version "3.2.0" version "3.2.0"
resolved "https://registry.yarnpkg.com/ansi-escapes/-/ansi-escapes-3.2.0.tgz#8780b98ff9dbf5638152d1f1fe5c1d7b4442976b" resolved "https://registry.yarnpkg.com/ansi-escapes/-/ansi-escapes-3.2.0.tgz#8780b98ff9dbf5638152d1f1fe5c1d7b4442976b"
...@@ -6588,6 +6588,13 @@ cli-cursor@^3.1.0: ...@@ -6588,6 +6588,13 @@ cli-cursor@^3.1.0:
dependencies: dependencies:
restore-cursor "^3.1.0" restore-cursor "^3.1.0"
cli-select@1.1.2:
version "1.1.2"
resolved "https://registry.yarnpkg.com/cli-select/-/cli-select-1.1.2.tgz#456dced464b3346ca661b16a0e37fc4b28db4818"
integrity sha512-PSvWb8G0PPmBNDcz/uM2LkZN3Nn5JmhUl465tTfynQAXjKzFpmHbxStM6X/+awKp5DJuAaHMzzMPefT0suGm1w==
dependencies:
ansi-escapes "^3.2.0"
cli-spinners@^1.1.0: cli-spinners@^1.1.0:
version "1.3.1" version "1.3.1"
resolved "https://registry.yarnpkg.com/cli-spinners/-/cli-spinners-1.3.1.tgz#002c1990912d0d59580c93bd36c056de99e4259a" resolved "https://registry.yarnpkg.com/cli-spinners/-/cli-spinners-1.3.1.tgz#002c1990912d0d59580c93bd36c056de99e4259a"
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment