Eslint adds unnecessary space between braces, Prettier shows error - javascript

I'm using prettier and eslint with typescript.
When I write some code and have to leave an empty function for reasons, Eslint and Prettier struggle adding and removing spaces between the empty function's braces.
Prettier is removing the space while Eslint is adding it.
What is expected:
constructor(
#inject('UsersRepository')
private usersRepository: IUsersRepository,
) {}
const example = ({ variable }) => {
console.log(variable)
};
What I get after saving (Eslint fixing on save):
constructor(
#inject('UsersRepository')
private usersRepository: IUsersRepository,
) { }
const example = ({ variable }) => {
console.log(variable)
};
Se the space between the constructor braces? That gives me a Delete `ยท` eslint(prettier/prettier) error.
When I save the file, or Prettier removes the space... then Eslint adds it again.
How can I solve this?
EDIT: I want to keep the destructuring assignment space (eg ({ variable })) but not on empty braces (eg {})
Below, my .eslintrc.json and prettier.config.js
{
"env": {
"es6": true,
"node": true,
"jest": true
},
"extends": [
"airbnb-base",
"plugin:#typescript-eslint/recommended",
"prettier/#typescript-eslint",
"plugin:prettier/recommended"
],
"globals": {
"Atomics": "readonly",
"SharedArrayBuffer": "readonly"
},
"parser": "#typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 2018,
"sourceType": "module"
},
"plugins": [
"#typescript-eslint",
"prettier"
],
"rules": {
"prettier/prettier": "error",
"class-methods-use-this": "off",
"#typescript-eslint/camelcase": "off",
"no-useless-constructor": "off",
"object-curly-spacing": [
"error",
"always"
],
"#typescript-eslint/no-unused-vars": [
"error",
{
"argsIgnorePattern": "_"
}
],
"#typescript-eslint/interface-name-prefix": [
"error",
{
"prefixWithI": "always"
}
],
"import/extensions": [
"error",
"ignorePackages",
{
"ts": "never"
}
]
},
"settings": {
"import/resolver": {
"typescript": {}
}
}
}
module.exports = {
singleQuote: true,
trailingComma: 'all',
arrowParens: 'avoid',
};

I've had very similar error, but in my case default VSCode TypeScript formatter was messing with braces.
In .vscode/settings.json add:
"javascript.format.insertSpaceAfterOpeningAndBeforeClosingEmptyBraces": false,
"typescript.format.insertSpaceAfterOpeningAndBeforeClosingEmptyBraces": false,
You might also find useful option:
"[typescript]": {
"editor.defaultFormatter": "dbaeumer.vscode-eslint"
}

You should use this in the settings file of vscode.
"prettier.bracketSpacing": false

I had the exact same problem, where prettier stopped working all of a sudden. Auto-format on save(vs code settings) adds a space for braces and linters threw an error on the same. Spend a lot of time debugging this and did the below steps to fix my issue
1: Re-install vscode prettier extension.
Go to vscode => cmd + p and type ext install esbenp.prettier-vscode.
2: My vscode settings.json and prettier.js looks somewhat like this
vscode settings.json
{
"editor.codeActionsOnSave": {
"source.organizeImports": true,
"source.fixAll.eslint": true,
"source.fixAll.tslint": true,
"source.fixAll.stylelint": true
},
"css.validate": false,
"files.autoSave": "off",
"typescript.updateImportsOnFileMove.enabled": "always",
"javascript.updateImportsOnFileMove.enabled": "always",
"editor.wordWrap": "on",
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": false,
"[typescriptreact]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
},
"[javascript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
},
"[typescript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
}
}
Prettier.js
module.exports = {
semi: true,
trailingComma: 'none',
singleQuote: true,
printWidth: 80,
tabWidth: 2,
endOfLine: 'auto',
bracketSpacing: true,
proseWrap: 'always'
};

I has a bad experience with prettier thanks to this post I managed to put together a nice settings config so Im sharing it here and hopefully it will ;help someone top.
"gatsbyhub.commands.build.enableTracing": true,
"gatsbyhub.commands.build.graphqlTracing": true,
"gatsbyhub.commands.develop.changeHost": "localhost",
"window.zoomLevel": 0.6,
"js/ts.implicitProjectConfig.checkJs": true,
"js/ts.implicitProjectConfig.experimentalDecorators": true,
"color-highlight.languages": [
"*",
],
"importCost.javascriptExtensions": [
"\\.jsx?$",
],
"html-css-class-completion.JavaScriptLanguages": [
"javascript",
"typescriptreact"
],
"editor.tabSize": 2,
"editor.renderWhitespace": "none",
"editor.gotoLocation.multipleTypeDefinitions": "goto",
"workbench.editor.enablePreviewFromCodeNavigation": true,
"workbench.editor.enablePreviewFromQuickOpen": true,
"debug.allowBreakpointsEverywhere": true,
"debug.toolBarLocation": "docked",
"blade.format.enable": true,
"color-highlight.matchWords": true,
"path-intellisense.showHiddenFiles": true,
"path-intellisense.mappings": {
"${workspaceFolder}": true,
"${workspaceFolder}/gatsby": true,
},
"editor.formatOnSave": false,
"editor.formatOnType": true,
"workbench.colorCustomizations": {},
"material-icon-theme.activeIconPack": "react_redux",
"editor.semanticHighlighting.enabled": false,
"editor.highlightActiveIndentGuide": false,
"workbench.activityBar.visible": false,
"javascript.format.enable": true,
"javascript.autoClosingTags": true,
"javascript.validate.enable": false,
"javascript.format.semicolons": "insert",
"javascript.suggest.jsdoc.generateReturns": true,
"javascript.format.insertSpaceBeforeFunctionParenthesis": true,
"javascript.preferences.quoteStyle": "double",
"javascript.preferences.useAliasesForRenames": true,
"javascript.suggest.autoImports": true,
"javascript.updateImportsOnFileMove.enabled": "always",
"javascript.format.insertSpaceAfterConstructor": true,
"[javascriptreact]": {
"editor.autoIndent": "advanced",
"editor.autoClosingQuotes": "beforeWhitespace",
"breadcrumbs.showVariables": true,
"diffEditor.ignoreTrimWhitespace": true,
"editor.tabSize": 2,
"editor.useTabStops": true,
"editor.formatOnPaste": false,
"editor.formatOnSaveMode": "file"
},
"javascript.suggest.includeCompletionsForImportStatements": true,
"javascript.format.insertSpaceBeforeAndAfterBinaryOperators": true,
"javascript.format.insertSpaceAfterSemicolonInForStatements": true,
"javascript.format.insertSpaceAfterKeywordsInControlFlowStatements": true,
"javascript.format.insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets": true,
"javascript.format.insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces": true,
"javascript.format.insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces": true,
"typescript.validate.enable": true,
"typescript.preferences.importModuleSpecifier": "non-relative",
"typescript.format.insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets": true,
I haven't started coding in typescript yet but when I do lll male a new config :)
Happy coding

Related

Eslint unable to find errors on .ts files

I generated SvelteKit project using npm create svelte#latest and added some .ts files for some library but running eslint . it cant find errors.
I have this default eslint config generate from svelte.
.eslintrc.cjs
module.exports = {
root: true,
parser: '#typescript-eslint/parser',
extends: ['eslint:recommended', 'plugin:#typescript-eslint/recommended', 'prettier'],
plugins: ['svelte3', '#typescript-eslint'],
ignorePatterns: ['*.cjs'],
overrides: [{ files: ['*.svelte'], processor: 'svelte3/svelte3' }],
settings: {
'svelte3/typescript': () => require('typescript')
},
parserOptions: {
sourceType: 'module',
ecmaVersion: 2020
},
env: {
browser: true,
es2017: true,
node: true
}
};
and tsconfig.json
{
"extends": "./.svelte-kit/tsconfig.json",
"compilerOptions": {
"allowJs": true,
"allowSyntheticDefaultImports": true,
"checkJs": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"sourceMap": true,
"strict": true
}
}
I have this lint on package.json
"lint": "prettier --check --plugin-search-dir=. . && eslint .",
Running npm run lint it cant find any errors even there is clearly an error to a .ts file.
It only can detect errors from .svelte files.
Is there something wrong with my eslint or tsconfig or I miss something?
My bad, it is linting the .ts files but some rules is missing from what i used to be and not showing errors so I add some rules instead of using the default one and now it showing errors.
Here is my new config
module.exports = {
root: true,
parser: '#typescript-eslint/parser',
extends: [
'eslint:recommended',
'plugin:node/recommended',
'plugin:#typescript-eslint/recommended',
'plugin:#typescript-eslint/recommended-requiring-type-checking',
'prettier'
],
plugins: ['node', 'prettier', 'svelte3', '#typescript-eslint'],
ignorePatterns: ['*.cjs', 'svelte.config.js', 'vite.config.js'],
overrides: [
{ files: ['*.svelte'], processor: 'svelte3/svelte3' },
{
files: ['*.ts', '*.js', '*.svelte'],
parser: '#typescript-eslint/parser',
extends: ['plugin:#typescript-eslint/recommended'],
rules: {
'node/no-missing-import': 'off',
'node/no-unpublished-import': 'off'
}
}
],
settings: {
'svelte3/typescript': () => require('typescript')
},
parserOptions: {
sourceType: 'module',
ecmaVersion: 2020,
project: ['./tsconfig.json']
},
env: {
browser: true,
es2017: true,
node: true
},
rules: {
'prettier/prettier': 'error',
'block-scoped-var': 'error',
eqeqeq: 'error',
'no-var': 'error',
'prefer-const': 'error',
'eol-last': 'error',
'prefer-arrow-callback': 'error',
'no-trailing-spaces': 'error',
quotes: ['warn', 'single', { avoidEscape: true }],
'no-restricted-properties': [
'error',
{
object: 'describe',
property: 'only'
},
{
object: 'it',
property: 'only'
}
]
}
};

Vuejs/Eslint/Prettier - Eslint complaining about tabwith and not correcting issues

Trying to get Eslint and Prettier to work on Vue projects. Having a couple of issues though.
For example, I have a rule setup is Eslint to add a space before function parens but it won't format:
Another issue is, I get a error about the tab width in the template section (but I've specified I want 4 spaces in Prettier). Any where would this rule be coming from? I haven't put 2 spaces for template section anywhere in the code:
As an FYI, I'm running Lunvarvim, which (not to blow too much smoke) is a great IDE which I'd like to continue to use if I can resolve this few pain points.
Here is my setup:
Eslint
module.exports = {
env: {
browser: true,
es6: true,
amd: true,
jquery: true,
jest: true,
'jest/globals': true,
},
extends: [
'plugin:jest/recommended',
'plugin:cypress/recommended',
'eslint:recommended',
'plugin:prettier/recommended',
'plugin:vue/recommended',
],
globals: {
Atomics: 'readonly',
SharedArrayBuffer: 'readonly',
$: true,
M: true,
Vue: true,
axios: true,
moment: true,
get: true,
process: true,
global: true,
accounting: true,
Qty: true,
Stripe: true,
Chart: true,
_: true,
},
parserOptions: {
parser: 'babel-eslint',
ecmaVersion: 2018,
sourceType: 'module',
},
plugins: ['vue'],
overrides: [
{
files: ['*.spec.js'],
rules: {
'no-unused-expressions': 0,
},
},
],
rules: {
'object-curly-spacing': ['error', 'always', { objectsInObjects: true }],
'space-in-parens': ['error', 'never'],
'array-bracket-spacing': ['error', 'never'],
'space-before-function-paren': ['error', 'always'],
'vue/component-name-in-template-casing': [
'error',
'kebab-case',
{
registeredComponentsOnly: true,
ignores: [],
},
],
'vue/no-unused-properties': [
'error',
{
groups: ['props', 'data', 'computed', 'methods'],
},
],
indent: ['error', 4],
'linebreak-style': 0,
'global-require': 0,
quotes: ['error', 'single'],
semi: ['error', 'always'],
'no-trailing-spaces': ['warn', { skipBlankLines: true }],
'eol-last': ['warn', 'always'],
'vue/html-self-closing': [
'error',
{
html: {
normal: 'any',
},
},
],
'vue/valid-v-slot': [
'error',
{
allowModifiers: true,
},
],
},
};
Prettier
{
"tabWidth": 4,
"singleQuote": true
}
Try to move the Prettier configuration into your package.json and make sure you have installed eslint-config-prettier

Attaching a function to window object in Webpack 5

I recently updated to Webpack 5 from Webpack 4, earlier I had a function on window object in index.js such that it looked something like
index.js
window.someFunction = function (...arguments) {
// function body
}
when this index.js gets bundled I can find this same function in common.bundle.js file.
and my index.html looks something like this
index.html
<head>
// rest of the head stuff
<script src="./dist/common.bundle.js"></script>
</head>
<body>
<script type="text/javascript">
someFunction(); // calling someFunction from the window object
// Also tried using window.someFunction() still doesn't work
</script>
</body>
In console I get ReferenceError: someFunction is not defined
and I am not able to print the function defination in chrome console when I type window.someFunction which was working in Webpack 4 as expected.
How do I attach my functions to window object in Webpack 5, and how do I go about accessing it?
webpack.config.js
const path = require("path");
const webpack = require("webpack");
module.exports = (env) => {
return {
mode: "development",
devtool: "source-map",
entry: {
common: "./index.js",
},
output: {
pathinfo: true,
path: path.join(__dirname, "dist"),
filename: "[name].bundle.js",
},
plugins: [
new webpack.DefinePlugin({
"process.env.NODE_ENV": JSON.stringify("development"),
}),
],
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: "babel-loader",
options: {
cacheDirectory: true,
babelrc: false,
presets: [
[
"#babel/env",
{
modules: false,
loose: true,
targets: {
browsers: [">0.25%", "not ie 11", "not op_mini all"],
},
},
],
"#babel/react",
],
plugins: [
[
"#babel/plugin-proposal-class-properties",
{
loose: true,
},
],
["#babel/plugin-transform-runtime"],
],
},
},
},
{
test: /\.css$/,
include: /node_modules/,
use: [{ loader: "style-loader" }, { loader: "css-loader" }],
},
],
},
resolve: {
extensions: [".js", ".jsx"],
modules: [path.resolve(__dirname, "node_modules")],
fallback: {
buffer: false,
fs: false,
tls: false,
net: false,
path: false,
zlib: false,
http: false,
https: false,
stream: false,
crypto: false,
},
},
optimization: {
// namedModules: true,
// namedChunks: true,
minimize: false,
// minimizer: [new TerserPlugin()],
runtimeChunk: "single",
moduleIds: "deterministic",
chunkIds: "deterministic",
nodeEnv: "development",
flagIncludedChunks: false,
concatenateModules: false,
splitChunks: {
hidePathInfo: false,
minSize: 20000,
maxAsyncRequests: Infinity,
maxInitialRequests: Infinity,
chunks: "all",
// maxSize: 0,
minChunks: 1,
automaticNameDelimiter: "~",
cacheGroups: {
commons: {
test: /[\\/]node_modules[\\/]/,
name: "other.bundle",
chunks: "all",
minChunks: 2,
},
defaultVendors: {
test: /[\\/]node_modules[\\/]/,
priority: -10,
},
default: {
minChunks: 2,
priority: -20,
reuseExistingChunk: true,
},
},
},
emitOnErrors: true,
checkWasmTypes: false,
removeAvailableModules: false,
},
performance: {
hints: "warning",
},
stats: {
all: false,
assets: true,
builtAt: true,
cachedAssets: false,
cachedModules: true,
chunkGroups: true,
colors: true,
env: true,
errors: true,
hash: true,
logging: "info",
timings: true,
modules: true,
outputPath: true,
performance: true,
errorsCount: true,
warnings: false,
warningsCount: true,
publicPath: true,
reasons: true,
ids: true,
version: true,
},
cache: {
type: "filesystem",
version: "1.0.0",
store: "pack",
name: "AppBuildCache",
maxMemoryGenerations: 1,
idleTimeout: 60000,
idleTimeoutAfterLargeChanges: 1000,
idleTimeoutForInitialStore: 0,
hashAlgorithm: "md4",
cacheLocation: path.resolve(__dirname, ".cache"),
},
externals: [
{
react: "React",
"react-dom": "ReactDOM",
jquery: "jQuery",
},
],
};
};
Try to add node.global: true to your config:
node: {
global: true
}
DoneDel0's comment was the correct solution for me.
node: {
global: true
}
The reasoning behind this is webpack 5 does no longer include a polyfills for node modules, so you have to manually set each.
https://webpack.js.org/configuration/node/#nodeglobal
However its good to note that the docs does suggest using ProvidePlugin instead of global.
Thank you for the answers, the issue turned out exactly to be due to missing polyfills for node core modules.
In my case the I had to provide polyfill for process using ProvidePlugin.
I did the same by adding below to my config
new webpack.ProvidePlugin({
process: "process/browser",
})
I added
node: {
global: true
}
but still the function is undefined in window object.

Prettier vscode json file indentation spacing issue

On save of any file, it is indenting with two tabs i.e 4 space in the beginning. Which rule is conflicting with prettier and .vscode settings?
Editor config settings are below:
root = true
[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
indent_style = space
indent_size = 2
trim_trailing_whitespace = true
max_line_length = 120
Trying to indent with 2 space, this is happening only
with json files and other scripts.
vscode settings
{
"[javascript]": {
"editor.formatOnSave": false
},
"eslint.alwaysShowStatus": true,
"files.autoSave": "onFocusChange",
"prettier.proseWrap": "preserve",
"emmet.includeLanguages": {
"javascript": "javascriptreact",
"vue-html": "html",
"plaintext": "jade",
"edge": "html"
},
"emmet.syntaxProfiles": {
"javascript": "jsx"
},
"emmet.triggerExpansionOnTab": true,
"emmet.showSuggestionsAsSnippets": true,
"files.associations": {
"*.js": "javascriptreact"
},
"editor.fontSize": 14,
"git.enableSmartCommit": true,
"git.confirmSync": false,
"search.exclude": {
"**/__snapshots__/**": true,
"**/.bin": true,
"**/.git": true,
"**/.next": true,
"**/bower_components": true,
"**/coverage/**": true,
"**/node_modules": false,
"**/node_modules/**": true,
"**/report/**": true,
"**/tmp": true
},
"javascript.updateImportsOnFileMove.enabled": "always",
"explorer.confirmDragAndDrop": false,
"explorer.confirmDelete": false,
"workbench.editor.enablePreviewFromQuickOpen": false,
"files.exclude": {
".next": true,
"*.log": true,
"**/__pycache__": true,
"**/o": true,
"dist": true,
"geckodriver.log": true,
"node_modules/": true,
"package-lock.json": true,
"yarn.lock": true
},
"window.zoomLevel": 1,
"editor.find.globalFindClipboard": true,
"editor.fontLigatures": true,
"jshint.enable": false,
"editor.formatOnType": true,
"team.showWelcomeMessage": false,
"git.autofetch": true,
"workbench.startupEditor": "newUntitledFile",
"editor.codeActionsOnSave": {
// For ESLint
"source.fixAll.eslint": true,
// For TSLint
"source.fixAll.tslint": true,
// For Stylelint
"source.fixAll.stylelint": true
},
"launch": {},
"workbench.colorCustomizations": {},
"sync.forceUpload": true,
"sync.forceDownload": true,
"sync.autoDownload": true,
"vetur.format.defaultFormatter.html": "js-beautify-html",
"intelephense.diagnostics.undefinedTypes": false,
"workbench.editorAssociations": [],
"diffEditor.codeLens": true,
"editor.formatOnSave": true,
"team.showFarewellMessage": false,
"eslint.validate": [],
"vetur.validation.template": false,
"prettier.enable": true,
"editor.formatOnPaste": true,
"editor.tabSize": 2,
"files.insertFinalNewline": true,
"[json]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.tabSize": 2
},
"[jsonc]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.tabSize": 2
},
"editor.tokenColorCustomizations": null
}
This was due to an extension: 'lonefy.vscode-js-css-html-formatter'.
You can add this rules for json files in your settings.json:
{
"[json]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.tabSize": 2
},
"[jsonc]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.tabSize": 2
}
}
And to be explicit, you can also add this one outside of the [json] block:
{
"prettier.tabWidth": 2
}
just add this line in your .prettierrc file, here written in yaml style
overrides:
- files: '*.json'
options:
semi: true
parser: 'json'
That's all folk's !

How can i improve code formatting using prettier configuration

I am using prettier with vs code with the option "editor.formatOnSave": true
Here is my .prettierrc config:
module.exports = {
semi: false,
overrides: [
{
files: ['*.js', '*.json', '*.css'],
options: {
trailingComma: 'es5',
tabWidth: 4,
semi: true,
singleQuote: true,
},
},
{
files: ['*.html'],
options: {},
},
],
};
is there a better way of doing that? and what should I put in the HTML option for a cleaner HTML code without having something like this:
<tr
ng-repeat="student in displayVars.studentsToShow track by student.id"
>
my HTML files should be in the one line something like that and I am not sure what's going on
<tr ng-repeat="student in displayVars.studentsToShow track by student.id">
by the way, I am using angulars 1 it's an old project to maintain.
we should add printWidth option to 1000
module.exports = {
semi: false,
overrides: [
{
files: ['*.js', '*.json', '*.css'],
options: {
trailingComma: 'es5',
tabWidth: 4,
semi: true,
singleQuote: true,
},
},
{
files: ['*.html'],
options: {
printWidth: 1000,
tabWidth: 4,
htmlWhitespaceSensitivity: 'ignore',
proseWrap: 'never',
},
},
],
};

Categories