Differences between Prettier CLI and VSCode extension - visual-studio-code

I tried to align VSCode extension and my local version of Prettier CLI in my project in order to get same results from both tools.
Prettier VSCode Extension : v9.10.4 (depends on prettier >=2.8.0)
Prettier : v2.8.0
With the following settings
// .vscode/settings.json
{
"prettier.documentSelectors": ["**/*.svg"],
"prettier.resolveGlobalModules": false,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"prettier.requireConfig": true,
"prettier.prettierPath": "./node_modules/prettier",
}
// .prettierrc
{
"printWidth": 80,
"semi": true,
"singleQuote": true,
"trailingComma": "es5",
"arrowParens": "always",
"bracketSameLine": false,
"overrides": [
{
"files": ["*.tsx"],
"options": {
"parser": "typescript"
}
}
]
}
And here is my test file
import * as React from 'react';
function Test() {
const [indicatorStyle, setIndicatorStyle] = React.useState<React.CSSProperties>({});
}
The "Format Document" option from VSCode gives this result
import * as React from 'react';
function Test() {
const [indicatorStyle, setIndicatorStyle] = React.useState<
React.CSSProperties
>({});
}
And the result from Prettier 2.8.0 CLI
import * as React from 'react';
function Test() {
const [indicatorStyle, setIndicatorStyle] =
React.useState<React.CSSProperties>({});
}
What should I do to get the same result instead (the result from Prettier CLI looks better in this case) ?
Thank you.

It seems to be related to a cache problem. After restarting VSCode I get the same results on both tools now!

Related

eslint not formatting index.ts on save

In vscode settings I have:
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true,
}
"eslint.enable": true,
"eslint.validate": [
"javascript",
"javascriptreact",
"typescript",
"typescriptreact",
],
When saving something.ts with this:
import { useContext } from 'react';
import { transactionsValueProps } from './interface';
import { TransactionsContext } from './TransactionsContext';
It moves import { TransactionsContext } from './TransactionsContext'; above import { transactionsValueProps } from './interface';. Not sure why because it's not alphabetically correct, but if that's the default of eslint, so be it.
However, when I save index.ts with this:
export * from './interface';
export * from './TransactionsContext';
export * from './useTransactionsContext';
It doesn't move things around. In fact, I can sort it as I wish, and nothing will get sorted.
How come? Am I missing something in vscode settings??

Unable to use Jest test in svelte component when carbon-icons-svelte is imported from inside node_modules error: Jest encountered an unexpected token

I would like to import an icon from package carbon-icons-svelte to my svelte component. It works very well in browser but I can't test this component. Testes worked good before import of carbon icons.
This is my configuration:
svelte.config.test.cjs
const preprocess = require('svelte-preprocess');
require('dotenv').config()
module.exports = {
preprocess: preprocess({
replace: [[/import.meta.env.([A-Z_]+)/, (importMeta) =>
{ return JSON.stringify(eval(importMeta.replace('import.meta', 'process')))} ]]
})
};
jest.config.cjs
const { pathsToModuleNameMapper } = require('ts-jest/utils');
const { compilerOptions } = require('./tsconfig.json');
module.exports = {
transform: {
'^.+\\.svelte$': [
'svelte-jester',
{
preprocess: './svelte.config.test.cjs'
}
],
"^.+\\.(js)$": "babel-jest",
'^.+\\.(ts)$': [require.resolve('jest-chain-transform'),
{ transformers: ['../../../build-utils/importMetaTransformer.cjs', 'ts-jest'] }
]
},
testMatch: ["**/spec/**/*.js"],
moduleFileExtensions: ['js', 'ts', 'svelte'],
setupFilesAfterEnv: ['<rootDir>/jest-setup.ts'],
moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths, {prefix: '<rootDir>/'})
};
tsconfig.json
{
"compilerOptions": {
"moduleResolution": "node",
"module": "es2020",
"lib": ["es2020", "DOM"],
"target": "es2019",
"importsNotUsedAsValues": "error",
"allowSyntheticDefaultImports": true,
"isolatedModules": true,
"resolveJsonModule": true,
"sourceMap": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"baseUrl": ".",
"allowJs": true,
"checkJs": true,
"paths": {
"$/*": ["src/*"]
}
},
"include": [
"src/**/*.d.ts",
"src/**/*.js",
"src/**/*.ts",
"src/**/*.svelte",
"src/**/*.svelte-kit",
"./jest-setup.ts"
],
"exclude": ["node_modules"]
}
I have this information about an error in jest:
Test suite failed to run
Jest encountered an unexpected token
Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.
Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.
By default "node_modules" folder is ignored by transformers.
Here's what you can do:
• If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/configuration
For information about custom transformations, see:
https://jestjs.io/docs/code-transformation
Details:
/home/dev/src/iroco-app-client/node_modules/carbon-icons-svelte/lib/Information32/Information32.svelte:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){<script>
^
SyntaxError: Unexpected token '<'
9 | import { createPopper } from '#popperjs/core';
10 | import Information32 from 'carbon-icons-svelte/lib/Information32/Information32.svelte';
> 11 |
| ^
I added to jest.config.test.cjs
transformIgnorePatterns: ["<rootDir>/node_modules/(?!(carbon-icons-svelte))"]
after moduleNameMapper but still it doesn't work.
Thanks for your help.
running on node 16, i changed my babel to cjs and it worked for me, this is what it looks like
module.export = {
presets: [['#babel/preset-env', { targets: { node: 'current' } }], '#babel/preset-typescript']
};
my jest.config.js
const config = {
testEnvironment: 'jsdom',
transform: {
'^.+\\.js$': 'babel-jest',
'^.+\\.ts$': 'ts-jest',
'^.+\\.svelte$': ['svelte-jester', { preprocess: true }]
},
transformIgnorePatterns: [
'<rootDir>/node_modules/(?!(carbon-icons-svelte))',
'<rootDir>/node_modules/(?!(carbon-components-svelte))'
],
moduleFileExtensions: ['js', 'ts', 'svelte']
};
export default config;

prettier doesn't format spacing between exported objects

I use prettier to format my typescript code with the following config. However, prettier doesn't fix spacing/blank line issues as you can see below in the code snippet. There is supposed to be a blank line between userSignupSchema and userLoginSchema and only one blank line between userLoginSchema and tokenSchema. I am using VS Code. Any idea how to fix this?
{
"extends": ["airbnb", "prettier", "plugin:node/recommended"],
"plugins": ["prettier"],
"rules": {
"prettier/prettier": "error",
"no-unused-vars": "warn",
"no-console": "off",
"func-names": "off",
"no-process-exit": "off",
"object-shorthand": "off",
"class-methods-use-this": "off"
},
"singleQuote": true
}
export const userSignupSchema = z.object({
name: z.string()
})
export const userLoginSchema = z.object({
name: z.string()
})
export const tokenSchema = z.object({
access_token: z.string()
})
Check the output of the ESLint extension: Ctrl + J to open the panel if it's not open → Output → ESLint. Your ESLint configuration is invalid. You can't have "singleQuote": true there. It's Prettier's option, so it should be specified in Prettier's configuration file.

vscode format modified lines with eslint

There are several developers working in my current project with different coding styles. Therefore, I need to configure my vscode with settings:
formatted only lines that were changed by me
formatting should run only when saving
possible to switch from eslint to tslint
My current config:
{
"editor.formatOnPaste": false,
"editor.formatOnType": false,
"editor.formatOnSave": false,
"editor.insertSpaces": true,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"[typescript]": {
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
}
},
"[javascript]": {
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
}
},
"[json]": {
"editor.formatOnSave": true
},
}
Well, I would also hope to hear how developers solve a similar problem when working in Vim (because sometimes I use it). Thank you!
The August 2020 update came with an option to "Only format modified"
https://code.visualstudio.com/updates/v1_49#_only-format-modified-text
That should cover 1. and 2. i belive.
If you want to format via eslint --fix, thats something that I'm looking for the answer to as well.
only "eslint --fix" modified lines

Cucumber (Gherkin) Full support extension for VS Code was unable to find step for

I'm using VS Code and Cucumber extension https://marketplace.visualstudio.com/items?itemName=alexkrechik.cucumberautocomplete&ssr=false#overview doesn't work.
This is my settings.json in .vscode folder:
{
"cucumberautocomplete.steps": [
"src/step_definitions/*.js",
],
"cucumberautocomplete.syncfeatures": "src/features/*feature",
"cucumberautocomplete.strictGherkinCompletion": true,
"cucumberautocomplete.strictGherkinValidation": true,
"cucumberautocomplete.smartSnippets": true,
"cucumberautocomplete.stepsInvariants": true,
// "cucumberautocomplete.pages": {
// "users": "test/features/page_objects/users.storage.js",
// "pathes": "test/features/page_objects/pathes.storage.js",
// "main": "test/features/support/page_objects/main.page.js"
// },
"cucumberautocomplete.skipDocStringsFormat": true,
"cucumberautocomplete.formatConfOverride": {
"And": 3,
"But": "relative",
},
"cucumberautocomplete.onTypeFormat": true,
"editor.quickSuggestions": {
"comments": false,
"strings": true,
"other": true
},
"cucumberautocomplete.gherkinDefinitionPart": "(Given|When|Then)\\(",
"cucumberautocomplete.stepRegExSymbol": "'"
}
And this is what I have added to settings.json of VS Code:
{
"workbench.colorTheme": "Default Light+",
"editor.quickSuggestions": true,
"window.zoomLevel": 0
}
When in my feature file I get the message for each line:
"Was unable to find step for "Given I am on the dashboard page"cucumberautocomplete"
Can someone help to resolve this issue and make it work for VS Code?
Kind regards,
mismas
So it finally worked when I:
I. deleted .vscode/settings.json (including the folder)
II. added following in global settings.json of Visual Sudio Code (the one in Users etc directory)
{
"workbench.colorTheme": "Default Light+",
"editor.quickSuggestions": true,
"window.zoomLevel": 0,
"gherkin-autocomplete.featuresPath": "src/features",
"cucumberautocomplete.steps": [
"src/step_definitions/*.js",
],
"cucumberautocomplete.syncfeatures": "src/features/*feature",
}
III. restarted VS Code
Either is something wrong with the plugin => meaning they didn't implemented as they think it should work or documentation is out dated ...
I had to remove the line
"cucumberautocomplete.stepRegExSymbol": "'"
and then it worked for me.
Just remove or comment on below line from setting.json
"cucumberautocomplete.stepRegExSymbol": "'"
It worked for me.
Windows10:
navigate to %APPDATA%\Code\User (which is VScode config folder)
add
"gherkin-autocomplete.featuresPath": "features",
"cucumberautocomplete.steps": [
"features/step_definitions/*.js",],
"cucumberautocomplete.syncfeatures": "features/*feature"
restart vscode