Wrong TSX ternary markup block formatting in VSCode - visual-studio-code

I like 'format on save' VSCode feature very much. But now I'm experiencing annoying wrong formatting of tsx files in VS Code (1.49.2).
Here is an example. Here two lines have extra indents ('single' block)
import React from 'react';
const TestComponent = (props: { isList: boolean }) => {
return (
<div>
{props.isList ? (
<div>liiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiist</div>
) : (
<div>siiiiiiiiiiiiiiiiiiiiiiiingle</div>
)}
</div>
);
};
export default TestComponent;
the same code in jsx file is formatted correctly
import React from 'react';
const TestComponent = props => {
return (
<div>
{props.isList ? (
<div>liiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiist</div>
) : (
<div>siiiiiiiiiiiiiiiiiiiiiiiingle</div>
)}
</div>
);
};
export default TestComponent;
I tried to switch default vscode formatter to eslint, null, prettier (user/workspace) - no difference. When I run prettier --write src/components/TestComponent.tsx the tsx file is formatted correctly.
I also checked typescript-specific formatting settings in VS Code, but couldn't find anything related. For the test I've removed .eslint.js config file and my project doesn't have .prettierrc config.

it was wrong formatter specified in $HOME/.config/Code/User/settings.json (on Linux), something like
"[typescriptreact]": {
"editor.defaultFormatter": "vscode.typescript-language-features"
}
it should be either set to esbenp.prettier-vscode or removed in order to use the default one

I fixed this problem by going to my user settings and deleting
"[javascript]": {
"editor.defaultFormatter": "vscode.typescript-language-features"
},
and configuring prettier to be the default formatter

Related

SvelteJS I added preferData to rollup.config.js, but it's ignored by vscode

I added this in rollup.config.js
plugins: [
svelte({
preprocess: sveltePreprocess({ sourceMap: !production, scss: {
prependData: "#import \"./src/scss/app.scss\";"
}})
}),
...etc
]
app.scss:
$v:red;
one of my svelte files:
value {
color: $v
}
but vscode showed me this error:
Error: undefined variable
color: $v;
code is working fine, but what can i do to avoid vscode showing me this error?
Assuming you used the Svelte Rollup template, add a svelte.config.js next to your rollup config with the following
const sveltePreprocess = require('svelte-preprocess');
module.exports = {
preprocess: sveltePreprocess({ scss: {
prependData: "#import \"./src/scss/app.scss\";"
}})
};
The Svelte for VS Code extension needs this file to understand what you are using besides Svelte itself in Svelte files. More info here: https://github.com/sveltejs/language-tools/blob/master/docs/preprocessors/in-general.md

SvelteKit console error "window is not defined" when i import library

I would like to import apexChart library which using "window" property, and i get error in console.
[vite] Error when evaluating SSR module /src/routes/prehled.svelte:
ReferenceError: window is not defined
I tried use a apexCharts after mount, but the error did not disappear.
<script>
import ApexCharts from 'apexcharts'
import { onMount } from 'svelte'
const myOptions = {...myOptions}
onMount(() => {
const chart = new ApexCharts(document.querySelector('[data-chart="profit"]'), myOptions)
chart.render()
})
</script>
I tried import a apexCharts when i am sure that browser exist.
import { browser } from '$app/env'
if (browser) {
import ApexCharts from 'apexcharts'
}
But i got error "'import' and 'export' may only appear at the top level"
I tried disable ssr in svelte.config.js
import adapter from '#sveltejs/adapter-static';
const config = {
kit: {
adapter: adapter(),
prerender: {
enabled: false
},
ssr: false,
}
I tried to create a component in which I import apexChart library and I created a condition that uses this component only if a browser exists
{ #if browser }
<ProfitChart />
{ /if }
Nothing helped.
Does anyone know how to help me please?
The easiest way is to simply include apexcharts like a standalone library in your webpage like this:
<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
And then simply use it in the onMount:
onMount(() => {
const chart = new ApexCharts(container, options)
chart.render()
})
You can add this line either in your app.html or include it where it's required with a <svelte:head> block.
An alternative way would be to dynamically import during onMount:
onMount(async () => {
const ApexCharts = (await import('apexcharts')).default
const chart = new ApexCharts(container, options)
chart.render()
})
As an extra: use bind:this instead of document.querySelector to get DOM elements, that would be the more 'svelte' way.
I have found the last option with the Vite plugin to work best with less code in the end but will lose intellisense in vscode and see import highlighted as error (temp workaround at end): https://kit.svelte.dev/faq#how-do-i-use-x-with-sveltekit-how-do-i-use-a-client-side-only-library-that-depends-on-document-or-window
Install vite plugin: npm i -D vite-plugin-iso-import
Add plugin to svelte.config.js:
kit: {
vite: {
plugins: [
isoImport(),
],
Add plugin to TypeScript config (if you use TS):
"compilerOptions": {
"plugins": [{ "name": "vite-plugin-iso-import" }],
Use as normal but note the "?client" on the import:
<script context="module">
import { chart } from 'svelte-apexcharts?client';
import { onMount } from 'svelte'
let myOptions = {...myOptions}
onMount(() => {
myOptions = {...updated options/data}
});
</script>
<div use:chart={myOptions} />
Debugging note:
To have import not highlighting as an error temporarily, just:
npm run dev, your project will compile fine, then test in browser to execute at least once.
remove ?client now, save and continue debugging as usual.
For all of you trying to import dynamically into a js or ts file, try the following:
Import your package during on mount in any svelte component.
onMount(async () => {
const Example = await import('#creator/examplePackage');
usePackageInJSOrTS(Example.default);
});
Use the imported package in your js/ts function. You need to pass the default value of the constructor.
export function usePackageInJsOrTs(NeededPackage) {
let neededPacakge = new NeededPackage();
}

Tailwind CSS autocomplete inside Twig variables

I am using TailwindCSS with TWIG files. The purgecss works fine inside CSS files and also inside "normal" markup like
<div class="font-bold text-blue"></div>
But we are developing mostly Drupal TWIG templates and a lot of our TWIG files setting classes to an attributes array. And the bellow doesn't work.
attributes.addClass(['font-bold', 'bg-blue']);
or
{% set classes = ['font-bold', color == 'blue' ? 'bg-blue'] %}
This is my purgecss configuration:
gulp.task(
"styles",
gulp.series("sass", function () {
const postcssimport = require("postcss-import");
return gulp
.src("src/styles.css")
.pipe(sass().on("error", sass.logError))
.pipe(
postcss([
postcssimport(),
tailwindcss("./tailwind.config.js"),
autoprefixer,
])
)
.pipe(
purgecss({
mode: "layers",
content: ["templates/**/*.twig", "src/scss/**/*.scss"],
defaultExtractor: (content) => content.match(/[\w-/:]+(?<!:)/g) || [],
})
)
.pipe(gulp.dest("./css"));
})
);
Do you have any idea about this?
Thank you.
The TailwindCSS Intellisense plugin for VS code has an experimental setting that lets you set custom regex expressions that fire autocomplete. It's announced by the plugin's author here:
https://github.com/tailwindlabs/tailwindcss-intellisense/issues/129#issuecomment-735915659
I use these 2 regular expressions to activate autocomplete for {% set classes = [] } and <element{{ attributes.addClass() }}> respectively:
"tailwindCSS.experimental.classRegex": [
["classes =.+\\[([^\\]]*)\\]","'([^']*)'"],
["addClass\\(([^\\)]*)\\)","'([^']*)'"]
]
This goes into the main settings.json file for VS Code.

VSCODE AND PRETTIER: Trailing ">"s causing rest of code to get formatted into a white text color

I'm using VSCODE with ESLINT and Prettier. When writing code, it appears that my editor is converting lines such as:
<template :slot="cancel">Cancel</template>
and putting the trailing >s on new lines:
<template :slot="cancel"
>Cancel</template
>
This causes VSCODE to show all the code in a a white font like so:
My prettier file:
module.exports = {
singleQuote: true,
semi: false,
printWidth: 200,
overrides: [
{
files: '*.html',
options: {
parser: 'html'
}
}
]
}
What is causing this and how to fix?

Jsx indentation conflict vscode and eslint

Eslint(airbnb config) wants to have my params on new lines when I have multiple params. But when I do that, vscode formatting keeps giving 4 spaces indentation instead of 2 as expected.
Result:
const Example = ({
param1,
param2,
param3,
}) => (
<div>
{param1} {param2} {param3}
</div>
);
expected:
const Example = ({
param1,
param2,
param3,
}) => (
<div>
{param1} {param2} {param3}
</div>
);
Is there a setting I can use in vscode to get the expected behavior?
You can avoid conflicting rules by using eslint-config-prettier or preferably prettier-eslint integration. This integration will use eslint config for formatting the rules and there won't be any conflicts.
If you are using VS Code, there is a config option for prettier-vscode