Align JavaScript imports "from" Statement to be Vertically Aligned - javascript

I would like the end result of my imports to be like this, via a tool that can automatically format my code onSave:
import { Stack, StackProps, Duration, Resource } from "aws-cdk-lib";
import { LambdaStack } from "./lambda-Stack";
import { Construct } from "constructs";
How can I align all of the "from" statements vertically in VS Code? I've looked at both prettier and eslint.

Prettier doesn't care what you want. :-) It's an opinionated tool useful for applying consistency to code within teams (and for avoiding arguments about different formatting styles [although you just get arguments about whether to use Prettier instead]).
If you don't want Prettier's formatting, don't use Prettier. There are other code formatters, some of which offer more control than Prettier does.
You could tell Prettier to ignore each of those import statements:
// prettier-ignore
import { Stack, StackProps, Duration, Resource } from "aws-cdk-lib";
// prettier-ignore
import { LambdaStack } from "./lambda-Stack";
// prettier-ignore
import { Construct } from "constructs";
or
/* prettier-ignore*/ import { Stack, StackProps, Duration, Resource } from "aws-cdk-lib";
/* prettier-ignore*/ import { LambdaStack } from "./lambda-Stack";
/* prettier-ignore*/ import { Construct } from "constructs";
For now there's no "block ignore" in Prettier for JavaScript (only for certain select other languages), although there's an open request for one.

Usually, with prettier or eslint you might want to limit printWidth to defined number of caracter per line. So imagine if you have many imports or long module name :
/* You better should break line overhere |----------| */
import { DepA, DepB, DepC, DepD, DepE, DepF, DepG, DepH, DepI, DepJ } from "./some-long-named-module";
import { OnlyOneImport } from "./other-module";
So my answer is not responding to "how can you align 'from' statements?" but it
may open another question 'should you ?'
Here is a common way to indent imports :
// common way to write import with vertical (Automatable)
import {
DepA,
DepB,
DepC,
DepD,
DepE,
DepF,
DepG,
DepH,
DepI,
DepJ
} from "./some-long-named-module";
import { OnlyOneImport } from "./other-module";
Here is the eslint rule to auto indent your code : https://eslint.org/docs/latest/rules/object-curly-newline
example for object-curly-newline rule in eslint:
# .estlintrc.json
{
...
"rules": {
...
"object-curly-newline": [
"error",
{
"consistent": true,
"multiline": true
}
]
}
}
PS:
Here some example of how I use it
# .estlintrc.json
{
"root": true,
"extends": [
"airbnb-base", // See https://www.npmjs.com/package/eslint-config-airbnb
"airbnb-base/whitespace",
"plugin:jest/recommended", // See https://www.npmjs.com/package/eslint-plugin-jest
"prettier" // See https://github.com/prettier/eslint-config-prettier
],
"env": {
"jest/globals": true
},
"plugins": [
"jest",
"...whatever-you-want"
],
"ignorePatterns": [
"dist/",
"node_modules/",
"...whatever-you-want"
],
"rules": {
"no-restricted-syntax": [
"error",
"WithStatement",
"BinaryExpression[operator='in']"
],
"no-console": [
0,
{
"allow": [
"info",
"warn",
"error"
]
}
],
"quotes": [
"error",
"single",
"avoid-escape"
],
"object-curly-newline": [
"error",
{
"consistent": true,
"multiline": true
}
],
"...whatever-you-want"
}
}
# .prettierrc
{
"printWidth": 80,
"trailingComma": "es5",
"useTabs": false,
"tabWidth": 2,
"semi": true,
"singleQuote": true,
"quoteProps": "as-needed",
"jsxSingleQuote": false,
"bracketSpacing": true,
"bracketSameLine": false,
"proseWrap": "preserve",
"arrowParens": "avoid",
"endOfLine": "lf",
"parser": "babel"
}

Related

prettier configuration is conflicting with eslint

Our project in company uses .js files and eslint is used for formatting. now we are transforming our app slowly to use .ts and .tsx files so I enabled prettier formatting in .ts and .tsx files only but before we use prettier we configured special rules for typescript files in eslint as following :
overrides: [
// Match TypeScript Files
// =================================
{
files: ['**/*.{ts,tsx}'],
// Parser Settings
// =================================
// allow ESLint to understand TypeScript syntax
// https://github.com/iamturns/eslint-config-airbnb-typescript/blob/master/lib/shared.js#L10
parser: '#typescript-eslint/parser',
parserOptions: {
project: './tsconfig.json',
},
// Extend Other Configs
// =================================
extends: [
'airbnb',
'plugin:#typescript-eslint/recommended',
'plugin:import/typescript',
],
rules: {
...rules,
'react/jsx-uses-react': 'off',
'react/react-in-jsx-scope': 'off',
'#typescript-eslint/space-before-blocks': 'error',
'#typescript-eslint/no-unused-vars': 'error',
'#typescript-eslint/explicit-function-return-type': 'error',
'#typescript-eslint/no-unsafe-return': 'warn',
'#typescript-eslint/padding-line-between-statements': [
'error',
{
blankLine: 'always',
prev: ['interface', 'type'],
next: '*',
},
],
'#typescript-eslint/member-delimiter-style': [
'error',
{
multiline: {
delimiter: 'none',
requireLast: false,
},
singleline: {
delimiter: 'comma',
requireLast: false,
},
},
],
'#typescript-eslint/type-annotation-spacing': 'error',
},
and in .prettierrc file I did the following :
{
"semi": true,
"singleQuote": true,
"printWidth": 100,
"arrowParens": "always",
"tabWidth": 2,
"trailingComma": "es5",
"bracketSameLine": false,
"bracketSpacing": true
}
so prettier for example adds semicolon at end of each line while this rule in .eslint
'#typescript-eslint/member-delimiter-style': [
'error',
{
multiline: {
delimiter: 'none',
requireLast: false,
},
singleline: {
delimiter: 'comma',
requireLast: false,
},
},
doesn't require the line to end with semicolon when declaring types and interface and many other rules conflicts also in eslint when adding multilpe empty lines in file it should show error so how I can do that with prettier?
You may need to change your default formatter for vscode to eslint. You can install the eslint extension and prettier Eslint.
If you are on mac this can be achieved by going to:
Code -> Preferences -> Settings -> Search for Default formatter -> change it to Eslint (dbaeumer.vscode-eslint).
You may also need to change your default formatter. You can achieve this by right-clicking in your screen -> Click on format document with.. -> configure default formatter

eslint no-use-before-define rules does not work in node.js

I use node.js 12.3.0 and i had installed eslint 7.0.0 by npm.
So i wrote the .eslintrc.js like below.
module.exports = {
"env": {
"commonjs": true,
"es6": true,
"node": true
},
"globals": {
"Atomics": "readonly",
"SharedArrayBuffer": "readonly"
},
"parserOptions": {
"ecmaVersion": 12
},
"rules": {
"semi": ["error", "always", {"omitLastInOneLineBlock": true }],
"no-shadow-restricted-names" : "error",
"no-unused-vars": ["warn", { "vars": "all" }],
"no-redeclare": ["error", { "builtinGlobals": true }],
"no-use-before-define": ["error", { "functions": true, "classes": true, "variables": true }]
}
};
As you know, i already added "no-use-before-define" but it didn't work.
All another eslint rules are worked fine but only "no-use-before-define" didn't check anythings.
Here is my examples js file.
let c = qwertqwert(); //As you know qwerqwert is not defined. I want to check this.
a = 123123; //I don't want to allow assign any value to variable before declaration.
b = asdfafasfdasdfas; //Also i need to check any undefined variable or functions are used.
Does "no-use-before-define" can check this?
It seems only can check when i use the variable or function before define or declaration.
Func(); //I use(call) first.
//But the define statement is after.
function Func()
{
return 10;
}
Above code had checked fine by eslint but it is meaningless.
Because i want let eslint to check usage of undefined functions or value.
if you define eslint should show the error you should write a rule like
if you don't want rule you can remove it or skip rule by file
"no-use-before-define": [
"error",
{
"functions": false,
"classes": false,
"variables": false
}
],
NOTE :- i am using extension of airbnb
extends: [
'airbnb-base',
],
it works for me
node js :- 14.17.6
eslint :- 7.12.1+
and if function is not defined then it shows

how to make .eslintrc accept single quotes

I am facing this error when I 'npm start' my project:
I already know the problem is in the .eslintrc file so I added this:
"rules": {
"quotes": [2, "single"],
}
and it's not working and it's the only solution I know
Update:
I tried deleting eslintConfig from package.json and it didn't work
and also "quotes": ["error", "single"] didn't work
You can try to turn the rule off by passing 0 in the .eslintrc config file:
{
"rules": {
"quotes": [0, "single"]
}
}
Based on the heading the solution is just to add a rule to allow single quotes. Refer below config, checkout rules object:
module.exports = {
env: {
browser: true,
es2020: true,
},
extends: ["eslint:recommended", "plugin:#typescript-eslint/recommended"],
parser: "#typescript-eslint/parser",
parserOptions: {
ecmaVersion: 11,
sourceType: "module",
},
plugins: ["#typescript-eslint", "prettier"],
rules: {
"prettier/prettier": [
1,
{
trailingComma: "es5",
//to enable single quotes
singleQuote: true,
semi: true,
},
],
...require("eslint-config-prettier").rules,
...require("eslint-config-prettier/#typescript-eslint").rules,
},
};
Try this out. If it doesn't work then share a bit more about the problem. May be write a small code try to replicate the issue and then share it here.
I hope this will help you out.
Cheers :)
Run eslint with the —fix flag and the problem will go away
I think you want to disable "quote" and "prettier/prettier" rules.
Please you can pass 0 to disable a rule.
{
"rules": {
"quotes": 0,
"prettier/prettier": 0
}
}

ESLint extends vs plugins v2020

There's answered question which in my opinion doesn't actually answers the question, on the difference between extends: [] vs plugins: [] in ESLint.
In my case, i just used extends section:
extends: [
'plugin:#typescript-eslint/recommended',
],
plugins: [],
rules: {
'#typescript-eslint/explicit-function-return-type': [
'error',
{
allowExpressions: true,
},
],
}
As you can see, i just used predefined config from plugin:#typescript-eslint/recommended and also overwritten #typescript-eslint/explicit-function-return-type rule in rules: {} section. But why do we need this PLUGINS section then? If everything works without it? What do i miss?
You have done it correctly.
For your example, there are 2 ways to do add typescript-eslint...
1st way:
{
parser: "#typescript-eslint/parser",
parserOptions: { sourceType: "module" },
plugins: ["#typescript-eslint"],
extends: [],
rules: {
"#typescript-eslint/explicit-function-return-type": [
"error",
{
allowExpressions: true
}
]
}
}
2nd way:
{
plugins: [],
extends: ["plugin:#typescript-eslint/recommended"],
rules: {
"#typescript-eslint/explicit-function-return-type": [
"error",
{
allowExpressions: true
}
]
}
}
The difference is...
1st way:
parser, parserOptions and plugins are manually added,
Only #typescript-eslint/explicit-function-return-type is enforced.
2nd way:
plugin:#typescript-eslint/recommended has automatically added parser, parserOptions and plugins.
Recommended typescript rules are added and enforced.
#typescript-eslint/explicit-function-return-type is augmented and enforced.
This is why when you use plugin:#typescript-eslint/recommended, things work normally even if plugins is empty. A well-written plugins/configs allows that to happen.

no-use-before-define wrongly catches use of the global window variable

Working in electron vue-cli project. Trying to upgrade eslint but the default setup has no-use-before-define enabled.
This causes it to catch every use of things like window.process.env.username as an error.
I tried setting my rules as "no-use-before-define": ["error", { "variables": false }], but it didn't help. Adding window as a global also didn't help. Is there a way to fix eslint to be happy with the window variable?
I do like the idea of this feature, so I would like to leave it on if possible. But just turning it off is ok too if that's the best answer.
If it helps, this is my current .eslintrc.js file
// https://eslint.org/docs/user-guide/configuring
module.exports = {
root: true,
parserOptions: {
parser: 'babel-eslint'
},
env: {
browser: true
},
extends: [
// https://github.com/vuejs/eslint-plugin-vue#priority-a-essential-error-prevention
// consider switching to `plugin:vue/strongly-recommended` or `plugin:vue/recommended` for stricter rules.
'plugin:vue/essential',
// https://github.com/standard/standard/blob/master/docs/RULES-en.md
'standard'
],
// required to lint *.vue files
plugins: [
'vue'
],
// add your custom rules here
rules: {
// Don't error on variables that are global, like window, not working.
"no-use-before-define": ["error", { "variables": false }],
'generator-star-spacing': 'off',
'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off',
"vue/html-self-closing": ["error", {
"html": {
"void": "always",
"normal": "any",
"component": "always"
},
"svg": "always",
"math": "always"
}]
}
}
Thanks
-Edit
Tried
globals: {
window: 'writable'
},
But to no effect

Categories

Resources