Git Product home page Git Product logo

prettier-plugin-svelte's People

Contributors

clebert avatar clitetailor avatar commanderroot avatar conduitry avatar curran avatar david-ding avatar dependabot[bot] avatar dummdidumm avatar ecogels avatar ehrencrona avatar ematipico avatar guidobouman avatar hyrious avatar hyunbinseo avatar jamesbirtles avatar jarrodldavis avatar jesseskinner avatar jrmajor avatar ktibow avatar mcuppi avatar opensas avatar orlov-vo avatar oscard0m avatar rolaka avatar ryanatkn avatar ryeballar avatar stijlmassi avatar taylorzane avatar techniq avatar toerndev avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

prettier-plugin-svelte's Issues

Error messages are swallowed

I'm not sure what the root cause is, maybe this needs to be fixed in prettier or svelte, but I'm not familiar enough with their architecture. You might know immediately where this belongs.

As mentioned in #70 I wasn't getting any meaningful error message. All I got was

[error] Unable to expand glob patterns: js/components/DetachableWindow.svelte !**/node_modules/** !./node_modules/** !**/.{git,svn,hg}/** !./.{git,svn,hg}/**
[error] Cannot read property 'line' of undefined

I was able to track this down to node_modules/svelte/compiler.js

	class CompileError extends Error {
	    toString() {
	        return `${this.message} (${this.start.line}:${this.start.column})\n${this.frame}`;
	    }
	}

where this.start is undefined. It should be this.loc.start. But I don't think something that obvious is a bug in svelte. Not sure what's going on here, since this is compiled from TypeScript.

Once I fixed the line I got

[error] js/components/DetachableWindow.svelte: <script> must have a closing tag
[error] > 1 | <script>
[error]     |        ^
[error]   2 |   import { onDestroy } from "svelte";
[error]   3 | 
[error]   4 |   let wrapperRef; (1:8)
[error] 1: <script>
[error]            ^
[error] 2:   import { onDestroy } from "svelte";
[error] 3: 

which helped a lot more.

Catch blocks are removed

When not using pending blocks, the catch block is removed:

Before formatting:

{#await dataP}
    {:then data}
      <div>Hey</div>
    {:catch error}
      <p style="color: red">{error}</p>
{/await}

After formatting:

{#await dataP then data}
    <div>Hey</div>
{/await}

Option to disable offset of the top level script tag

Considering this code:

<script>
	export const foo = 123
</script>

<h1>foo = {foo}</h1>

can there be at least the option to disable indentation of the script? It looks awful especially in complex components, where like 80% of code becomes indented for no reason.

prettier itself defaults to not indent first-level SFC tags (prettier/prettier#3888).

SCSS parsing

What's the best way to let Prettier parse the <style> tags as SCSS?

Sorting order

The current default sorting order is "script > style > html". My prefer sorting order is "html > style > script". Is there any option for that?

option for shortened await blocks

According to the documentation, the pending status may be skipped. Also, the catch block may be omitted:

{#await promise then value}
  <p>The value is {value}</p>
{/await}

At the moment prettier enforces this format:

{#await promise}

{:then value}
  <p>The value is {value}</p>
{:catch}

{/await}

Which leads to Empty block warnings. Workaround is adding empty comments, which is not really pretty.

Could the shorthand syntax be added? ๐Ÿ˜ƒ

Prettier.config

Can i use prettier.config.js for plugin?

module.exports = {
  tabWidth: 2,
  semi: true,
  singleQuote: true,
  plugins: ['prettier-plugin-svelte']
};

error with prettier 2.0.1

I get errors when trying with prettier
src/App.svelte: Error: unknown node type: MemberExpression

Namespace `sortOrder` option

The sortOrder option has a high chance of conflicting with other prettier plugins. I suggest svelteSortOrder.

I use a prettier modification that sorts css properties and has a sortOrder option as well.

HTML formatting differs in .svelte and .html files

I have markup for a component like this:

<div>
    <a href="/some-long-href-lorem-ipsum/">Lorem ipsum lorem ipsum 1</a>,
    <a href="/some-long-href-lorem-ipsum/">Lorem ipsum lorem ipsum 2</a>,
    <a href="/some-long-href-lorem-ipsum/">Lorem ipsum lorem ipsum 3</a>
</div>

If I put this code into a component.html file and let prettier format it then the formatting stays as it is above.

However if I put this markup into a component.svelte file then it gets formatted to this:

<div>
    <a href="/some-long-href-lorem-ipsum/">Lorem ipsum lorem ipsum</a>
    ,
    <a href="/some-long-href-lorem-ipsum/">Lorem ipsum lorem ipsum</a>
    ,
    <a href="/some-long-href-lorem-ipsum/">Lorem ipsum lorem ipsum</a>
</div>

This is a problem if the a tags are styled as display: inline-block;. To avoid I have the folllowing setting in my .prettierrc file:

{ "htmlWhitespaceSensitivity": "strict" }

I suppose that prettier-plugin-svelte somehow doesn't regard this setting.

Option to disable attribute shorthand on format.

In VSCode for example in component i have:

<script>
export let value;
</script>

<input type="text" value="{value}" />

after format i get:

<input type="text" {value}>

Is there any option to disable this?

Want to transfer this to the sveltejs org and make it an official plugin?

Hi there! Would you be interested in the Svelte maintainers adopting this and it becoming an official plugin?

I'm using Svelte and Prettier at work, and I've recently gotten the okay to spend work hours on this, so for the immediate future it would probably be me doing the renovating and refreshing. I've also spoken with other Svelte maintainers and they agree that this is something it would be good to have an official solution for.

Let me know! Thanks!

SyntaxError: Unexpected closing tag "div".

Hello!
First of all, thank you for your work!
I've just cloned repo, all tests passed, but I find out that if I execute
prettier test/formatting/samples/**/*.html
than I have error

test/printer/samples/v3/animation-with-expression.html[error] test/printer/samples/v3/animation-with-expression.html: SyntaxError: Unexpected closing tag "div". It may happen when the tag has already been closed by another tag. For more info see https://www.w3.org/TR/html5/syntax.html#closing-elements-that-have-implied-end-tags (2:55)
[error]   1 | {#each things as thing (thing)}
[error] > 2 |     <div animate:flip={{ delay: i * 10 }}>{thing.name}</div>
[error]     |                                                       ^
[error]   3 | {/each}
[error]   4 | 

What I missed?

Error: No parser could be inferred for file

Why I try to run prettier on .svelte files using this plugin, I get an error

[error] No parser could be inferred for file: <FILE_NAME>

This is my configuration file

{
  "useTabs": true,
  "printWidth": 80,
  "singleQuote": true,
  "plugins": ["svelte"]
  
}

And this is what I run via CLI

prettier --write "./**/*.svelte"

Self closed custom elements

I get the following error: "Only void and foreign elements can be self closed".

<script>
  import Test from './Test.svelte';
</script>

<Test />

Configuration help

Hi! Sorry if this is really basic, but I have difficulties configuring prettier-plugin-svelte with a configuration file in VS Code. The Svelte extension is installed and I created a prettierrc.json file like so:

{
  "trailingComma": "es5",
  "tabWidth": 2,
  "arrowParens": "always",
  "bracketSpacing": true,
  "endOfLine": "lf",
  "printWidth": 80,
  "singleQuote": false,
  "svelteSortOrder" : "scripts-markup-styles",
  "svelteStrictMode": true,
  "svelteBracketNewLine": false,
  "svelteAllowShorthand": false
}

Some configuration is for standard Prettier with JS. However, whatever the values I use for the svelte options, it doesn't seem to make any difference when I format a .svelte file. For example, even with "svelteAllowShorthand: false", the shorthand {id} won't be reformatted to id={id}:

<div class="ui input" class:transparent="{!focussed}" {id}>

Thanks for your kind help!

Empty style and script tags are expanded into three lines

I'm using Svelte with svelte-preprocessor. The following lines:

<script src="./index.ts"></script>

<style src="./index.css"></style>

is formatted as:

<script src="./index.ts">

</script>

<style src="./index.css">

</style>

My expected output should be the same as first one. Is this some kind of bug?

Thanks!

HTML whitespace is not maintained.

Wrapping a word just before punctuation, but not wrapping the punctuation, results in bad formatting.

<p>This is a <strong>bold stance</strong>.</p>

becomes

<p>
  This is a
  <strong>bold stance</strong>
  .
</p>

Which is rendered as:

This is a bold stance .

Notice the space before the period.

ElseBlock breaks each/else block

I encountered a problem when nesting an {#if} block in an {#each}...{:else} block.

The logic detects the if child of the else block and turns the {#each}...{:else} into an {#each}...{:else if} block which is invalid Svelte.

Adding a node between the {:else} and the {#if} prevents the clobbering, but I'd rather not have to put in dummy <div>s or comments.

Example:

Input

{#each items as item}
{item.name}
{:else}
  {#if label}
  We have no {label}s.
  {:else}
  We have no widgets.
  {/if}
{/each}

Output

{#each items as item}
{item.name}
{:else if label}
We have no {label}s.
{:else}
We have no widgets.
{/each}

I might also extend this bug into a request for disabling this particular formatting rule. There are some cases where switching a nested if/if block into an if/else if/else block can cause some semantic differences during evaluation, also readability could be argued for nested if/if blocks.

I can try taking a stab at this if I have some time, but don't let that stop anyone else from trying to tackle it.

False positive: component can only have one instance-level <script> element

The following Svelte component:

<script></script>

<div>
  hello!
  <script>alert(1)</script>
</div>

makes the plugin crash with:

1.svelte[error] 1.svelte: ParseError: A component can only have one instance-level <script> element
[error]     at error$1 (/Users/semenov/test/node_modules/svelte/compiler.js:13491:20)
[error]     at Parser$2.error (/Users/semenov/test/node_modules/svelte/compiler.js:13567:10)
[error]     at Object.parse$2 [as parse] (/Users/semenov/test/node_modules/svelte/compiler.js:13669:17)
[error]     at Object.parse (/Users/semenov/test/node_modules/prettier-plugin-svelte/plugin.js:532:47)
[error]     at Object.parse$2 [as parse] (/Users/semenov/test/node_modules/prettier/bin-prettier.js:10635:19)
[error]     at coreFormat (/Users/semenov/test/node_modules/prettier/bin-prettier.js:13844:23)
[error]     at format (/Users/semenov/test/node_modules/prettier/bin-prettier.js:14102:73)
[error]     at formatWithCursor (/Users/semenov/test/node_modules/prettier/bin-prettier.js:14118:12)
[error]     at Object.formatWithCursor (/Users/semenov/test/node_modules/prettier/bin-prettier.js:42529:15)
[error]     at format$1 (/Users/semenov/test/node_modules/prettier/bin-prettier.js:43898:21)
error Command failed with exit code 2.

However it's not the instance level script, it's perfectly valid Svelte code: sveltejs/svelte#335


ALSO, the plugin will crash with the same error even if the script tag is commented!

<script></script>

<div>
  hello!
  <!-- <script>alert(1)</script> -->
</div>

Neoformat support

This isn't an issue so much as a heads up and search reference for others. I added this (sort of) to Neoformat for vim use.

Thanks for the sweet plugin!

"Crash" when used with prettier and eslint

Please see sveltejs/svelte#3550 for details, though is closed there.
I copied the original bug report here, thanks

Describe the bug
With this template where we want ESLint to co exist with prettier I have 2 problems when the plugins are nebale with this config

As described in the prettier docs this enable ESLint to call prettier

  1. Lint crashes in the svlte compile - see stack trace
  2. Prettier fails to format on save the App.svelte file - and error flashes up in the status bar

Logs
see stack trace

To Reproduce
Uncommented the line aboveand comment the one above it

  1. Run npm run lint from the command line
  2. edit the App.svelte and save the file

Expected behavior

  1. no error and llinter succeeds
  2. File is reformated via prettier

Stacktraces

Stack trace

$ npm run lint

[email protected] lint C:\projects\svelte-code-cypress-project
eslint src/*

ParseError: Expected }
1 | export let name
2 |

3 | {name;name=0}
| ^
Occurred while linting C:\projects\svelte-code-cypress-project\src\App.svelte:3
at error$1 (C:\projects\svelte-code-cypress-project\node_modules\svelte\compiler.js:13329:20)
at Parser$2.error (C:\projects\svelte-code-cypress-project\node_modules\svelte\compiler.js:13405:10)
at Parser$2.eat (C:\projects\svelte-code-cypress-project\node_modules\svelte\compiler.js:13419:19)
at mustache (C:\projects\svelte-code-cypress-project\node_modules\svelte\compiler.js:13220:17)
at new Parser$2 (C:\projects\svelte-code-cypress-project\node_modules\svelte\compiler.js:13364:22)
at Object.parse$1 [as parse] (C:\projects\svelte-code-cypress-project\node_modules\svelte\compiler.js:13495:21)
at Object.parse (C:\projects\svelte-code-cypress-project\node_modules\prettier-plugin-svelte\plugin.js:669:51)
at Object.parse$2 [as parse] (C:\projects\svelte-code-cypress-project\node_modules\prettier\index.js:10629:19)
at coreFormat (C:\projects\svelte-code-cypress-project\node_modules\prettier\index.js:13888:23)
at format (C:\projects\svelte-code-cypress-project\node_modules\prettier\index.js:14146:73)
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! [email protected] lint: eslint src/*
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the [email protected] lint script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\steve\AppData\Roaming\npm-cache_logs\2019-09-11T17_00_42_583Z-debug.log

Information about your Svelte project:

  • Your browser and the version: (e.x. Chrome 52.1, Firefox 48.0, IE 10)
    Not relevant - build error

  • Your operating system: (e.x. OS X 10, Ubuntu Linux 19.10, Windows XP, etc)
    Windows 10 latest 1903

  • Svelte version (Please check you can reproduce the issue with the latest release!)
    3.12.1

  • Whether your project uses Webpack or Rollup
    Roll up

Severity
How severe an issue is this bug to you? Is this annoying, blocking some users, blocking an upgrade or blocking your usage of Svelte entirely?

Serious - can't lint or run prettier on svelte files

Additional context
Add any other context about the problem here.

Configure whitespace-sensitive tags

Related to #24, whitespace-sensitive tags should not be modified on format. For example, this

    <pre>foo
bar baz</pre>

becomes this

    <pre>foo bar baz</pre>

I would also like to be able to configure custom tags to follow the same rules as the <pre> tag. For example, if I configure the CodeSnippet tag to be whitespace-sensitive, this should not change after formatting:

    <CodeSnippet lang="js">const foo = () => {
  return 42
}</CodeSnippet>

Closing angle bracket differs from prettier HTML.

Given a tag that has its attributes spread across lines, prettier will add the closing angle bracket on a new line, like this:

<span
  some="long"
  list="of"
  attributes
>
  Content
</span>

But prettier-plugin-svelte will put the angle bracket on the line with the last attribute, like this:

<span
  some="long"
  list="of"
  attributes>
  Content
</span>

Unknown node Options

The <svelte:options> does not have handling and causes prettier-plugin-svelte to throw an error.

The options (and all other <svelte:*> elements should be added (or check if they already exist) to the printer.

I'll try to submit a PR for this this afternoon. If someone wants to tackle it instead, go for it.

Choose what to format

Hello,
First of all, thank you for your work. I'm currently using your plugin via the vscode extension but I posted the issue here as I think it is more appropriate.
I'm using pug templating so I have 3 main tags in my files : template, script and style. Currently, the plugin does not give you the opportunity to choose what to format and I ended up deactivating formatting because it messes up my pug template.
Would it be possible to activate/deactivate formatting for script/style/template independently as it is the case for Vue with Vetur?
Thank you.

Does not work with Typescript

It appears this fails when using <script lang="ts">.

npm i -D prettier prettier-plugin-svelte
npx prettier --write ./**/*.svelte

Generates the following errors. I used this Typescript template with no modifications.

src/App.svelte
[error] src/App.svelte: TypeError: require(...).parse is not a function
[error]     at Object.parse (/Users/danawoodman/code/playground/svelte-app/node_modules/prettier-plugin-svelte/plugin.js:532:47)
[error]     at Object.parse$2 [as parse] (/Users/danawoodman/code/playground/svelte-app/node_modules/prettier/bin-prettier.js:10635:19)
[error]     at coreFormat (/Users/danawoodman/code/playground/svelte-app/node_modules/prettier/bin-prettier.js:13844:23)
[error]     at format (/Users/danawoodman/code/playground/svelte-app/node_modules/prettier/bin-prettier.js:14102:73)
[error]     at formatWithCursor (/Users/danawoodman/code/playground/svelte-app/node_modules/prettier/bin-prettier.js:14118:12)
[error]     at Object.formatWithCursor (/Users/danawoodman/code/playground/svelte-app/node_modules/prettier/bin-prettier.js:42529:15)
[error]     at format$1 (/Users/danawoodman/code/playground/svelte-app/node_modules/prettier/bin-prettier.js:43898:21)
[error]     at /Users/danawoodman/code/playground/svelte-app/node_modules/prettier/bin-prettier.js:44093:16
[error]     at /Users/danawoodman/code/playground/svelte-app/node_modules/prettier/bin-prettier.js:44033:14
[error]     at Array.forEach (<anonymous>)
src/Counter.svelte
[error] src/Counter.svelte: TypeError: require(...).parse is not a function
[error]     at Object.parse (/Users/danawoodman/code/playground/svelte-app/node_modules/prettier-plugin-svelte/plugin.js:532:47)
[error]     at Object.parse$2 [as parse] (/Users/danawoodman/code/playground/svelte-app/node_modules/prettier/bin-prettier.js:10635:19)
[error]     at coreFormat (/Users/danawoodman/code/playground/svelte-app/node_modules/prettier/bin-prettier.js:13844:23)
[error]     at format (/Users/danawoodman/code/playground/svelte-app/node_modules/prettier/bin-prettier.js:14102:73)
[error]     at formatWithCursor (/Users/danawoodman/code/playground/svelte-app/node_modules/prettier/bin-prettier.js:14118:12)
[error]     at Object.formatWithCursor (/Users/danawoodman/code/playground/svelte-app/node_modules/prettier/bin-prettier.js:42529:15)
[error]     at format$1 (/Users/danawoodman/code/playground/svelte-app/node_modules/prettier/bin-prettier.js:43898:21)
[error]     at /Users/danawoodman/code/playground/svelte-app/node_modules/prettier/bin-prettier.js:44093:16
[error]     at /Users/danawoodman/code/playground/svelte-app/node_modules/prettier/bin-prettier.js:44033:14
[error]     at Array.forEach (<anonymous>)

Incorrect formatting of HTML in some cases

HTML like this:

<div>
  <MyIcon />
  Current score: [{score}]
</div>

gets formatted like this:

<div>
  <MyIcon />
  Current score: [
  {score}
  ]
</div>

At first glance, this looks fine, but the issue is that these two HTML segments are actually displayed differently in the browser. Assume the score is 10.

  • The first segment is displayed like so: Current score: [10]
  • The second segment is displayed like so: Current score: [ 10 ]

Notice the extra spaces inside the brackets.

options for formatting HTML

Is there a possibility to put trailing angle bracket of long HTML tag on the new line during the formatting, please?

Currently, the output I get is:

<a
    class={segment === 'sign-in' ? 'selected' : ''}
    href={$user.id === undefined ? 'sign-in' : 'my-profile'}
    cy="profile">
    {$user.id === undefined ? 'sign-in' : 'my-profile'}
</a>

I would prefer it like this (note the trailing > on the newline and the single quotes converted to double quotes):

<a
    class={segment === "sign-in" ? "selected" : ""}
    href={$user.id === undefined ? "sign-in" : "my-profile"}
    cy="profile"
>
    {$user.id === undefined ? "sign-in" : "my-profile"}
</a>

The prettier playground does it exactly like preffered, see link

Transition modifier is removed

This is happening for me at the moment

<div transition:fade|local> -> <div transition:fade>

Not sure if it applies to all modifiers or just this one for transition.

Unwanted linebreaks

I have a line that looks like this.

or simply <code>/</code>.

Prettier formats it into this

  or simply
  <code>/</code>
  .

The result is a space before the period, which is highly unwanted.

I've had similar issues where I couldn't allow white spaces between tags, but prettier forced them in anyway.

I've tried adding a .prettierrc.json

{
  "preserveWhitespaces": true
}

But to no avail.

Is there any way around this?

HTML entities not preserved

HTML entities in templates are replaced with their literal equivalents. For example

5 &lt; 6

is transformed into

5 < 6

This can cause encoding issues with unicode entities and compile errors with < and >.

Error: Unrecognized option 'onwarn'

The Console Log

> [email protected] format /home/beenotung/workspace/local/gcms/gcms-client
> prettier --write --plugin-search-dir=. ./src/*.{svelte,html}

src/App-bug-report.svelte
[error] src/App-bug-report.svelte: Error: Unrecognized option 'onwarn'
[error]     at Object.keys.forEach.key (/home/beenotung/workspace/local/gcms/gcms-client/node_modules/svelte/compiler.js:23582:20)
[error]     at Array.forEach (<anonymous>)
[error]     at validate_options (/home/beenotung/workspace/local/gcms/gcms-client/node_modules/svelte/compiler.js:23576:27)
[error]     at Object.compile (/home/beenotung/workspace/local/gcms/gcms-client/node_modules/svelte/compiler.js:23618:6)
[error]     at parse (/home/beenotung/workspace/local/gcms/gcms-client/node_modules/prettier-plugin-svelte/plugin.js:501:27)
[error]     at Object.parse (/home/beenotung/workspace/local/gcms/gcms-client/node_modules/prettier-plugin-svelte/plugin.js:523:20)
[error]     at Object.parse$2 [as parse] (/home/beenotung/workspace/local/gcms/gcms-client/node_modules/prettier/bin-prettier.js:10635:19)
[error]     at coreFormat (/home/beenotung/workspace/local/gcms/gcms-client/node_modules/prettier/bin-prettier.js:13844:23)
[error]     at format (/home/beenotung/workspace/local/gcms/gcms-client/node_modules/prettier/bin-prettier.js:14103:73)
[error]     at formatWithCursor (/home/beenotung/workspace/local/gcms/gcms-client/node_modules/prettier/bin-prettier.js:14119:12)

The Sample Source

<script>
	export let name = 'admin';
	let databases = [];
	let databaseName = '';
	let apiEndpoint = {
	  host: 'localhost',
	  port: 3000
	};
	let apiBaseUrl = '';
	$: apiBaseUrl = 'http://' + apiEndpoint.host + ':' + apiEndpoint.port + '/admin/';

	let res;

	function checkApiResult(res){
	  let {status} = res;
	  if(!(200<=status && status<300)){
	    return res.json().then(x=>Promise.reject(x));
	  }
	  let contentType = res.headers.get('Content-Type');
	  if(contentType&&contentType.startsWith('application/json')){
	    return res.json();
	  }
	  return res;
	}
	let mockDBs = ['db1','db2'].map(name=>({name}));
	function mockFetch(url,{data}) {
	  if(url.endsWith('databases')){
	    return Promise.resolve({status:200,headers:{get:()=>'application/json'},json:()=>Promise.resolve(mockDBs)})
	  }
	  if(url.endsWith('database')){
	    mockDBs.push(data);
	    return Promise.resolve({status:201,headers:{get:()=>'text'}});
	  }
	  return Promise.resolve({status:400,headers:{get:()=>'text'},statusText:'unknown api'});
	}
	fetch = mockFetch;
	function apiCall({url,method,data}){
	  let headers = [['Content-Type','application/json']];
	  let body = JSON.stringify(data);
	  return fetch(apiBaseUrl+url,{method,body,headers})
	    .then(res=>checkApiResult(res))
	}

	function loadAllDatabases(){
	  res = apiCall({url:'databases'});
	  res.then(xs=>databases=xs);
	}
	function createDatabase(){
	  res = apiCall({
	    url:'database',
	    method: 'post',
	    data: {database:{
	      name: databaseName,
	      tables: []
	    }}
	  });
	  res.then(()=>loadAllDatabases());
	}

	function format(o) {
	  return '<pre>' + JSON.stringify(o,null,2) + '</pre>';
	}
</script>

<style>
</style>


<h2>Database</h2>
<input type="button" value="Load All Database" on:click="{loadAllDatabases}">
<h3>Database Names</h3>
<ul>
{#each databases as {name} (name)}
<li>{name}</li>
{/each}
</ul>
<p>Total number of database: {databases.length}</p>

<label for="database">New Database Name</label>
<input id="database" bind:value="{databaseName}">
<input type="button" value="Create Database" on:click="{createDatabase}">

<h2>API Result</h2>
{#await res}
waiting...
{:then result}
resolve: {@html format(result)}
{:catch error}
reject: {@html format(error)}
{/await}

prettier-ignore is ignored

The following snippet of code will get formatted regardless of whether the <!-- prettier-ignore --> comment is above the line. The standard prettier html parser handles this case.

<script>
// whatever
</script>

<!-- prettier-ignore -->
<span>[</span><span>{value}</span><span>]</span>

<style>
/* whatever */
</style>

The spans need to stay on one line as this component is inside of a <pre> tag and being on new lines modifies the outcome. (That's a separate issue that can't necessarily be handled by #28, so the prettier-ignores should be respected.)

"svelteBracketNewLine" does not working

Hello! Thanks for this extension!
I restored issue #66 because the "svelteBracketNewLine" option does not work. I specified in the .prettierrc file, but it does not change the position of the closing bracket. I also inserted the option "svelteBracketNewLine" in the .prettierrc.js file, and there was also the option of closing the angle bracket without a slash, the result does not change.
image

Handling long text and inline elements

Currently, the plugin breaks at the start and end of child content when it can't fit on one line:

--- input.html	2019-05-12 16:49:09.000000000 -0600
+++ output.html	2019-05-12 16:49:09.000000000 -0600
@@ -1 +1,5 @@
-<span>Lorem ipsum dolor sit amet consectetur adipisicing elit. Tenetur ad fugit cupiditate vel ullam voluptatum maxime harum nemo ipsa sequi sapiente assumenda vitae, beatae iste sed veritatis ipsam dicta deserunt.</span>
+<span>
+    Lorem ipsum dolor sit amet consectetur adipisicing elit. Tenetur ad fugit
+    cupiditate vel ullam voluptatum maxime harum nemo ipsa sequi sapiente
+    assumenda vitae, beatae iste sed veritatis ipsam dicta deserunt.
+</span>

Usually, this isn't a problem, but it can be an issue if the parent element (in the above example, <span>) has a display CSS property with a value of inline. In that case, an extra space will be present between sibling nodes that may be undesirable, especially when surrounded by other inline elements or non-whitespace text.

Another cause of likely unwanted wrapping is when an inline element is present as a child element.

Here is an example, similar to #14:

--- input.html	2019-05-12 17:17:01.000000000 -0600
+++ output.html	2019-05-12 17:17:01.000000000 -0600
@@ -1,3 +1,5 @@
 <div>
-    [<span>{score}</span>]
+    [
+    <span>{score}</span>
+    ]
 </div>

Perhaps the easiest way to rectify both issues is to hardcode a list of inline elements when checking if a node is an inline node:

https://github.com/UnwrittenFun/prettier-plugin-svelte/blob/771df545e15f422a9597e9153a1518dbbba8c079/src/print/index.ts#L467-L469

This will cause the element to be treated as part of the inline sequence fill groups already used in printChildren โ€“ this will allow the element's tags to remain in its current position and only break between words when necessary, not forcibly before the start tag and at the start and end of the element's child content.

For example:

--- input.html	2019-05-12 17:30:45.000000000 -0600
+++ output.html	2019-05-12 17:30:45.000000000 -0600
@@ -1 +1,3 @@
-<span>Lorem ipsum dolor sit amet consectetur adipisicing elit. Tenetur ad fugit cupiditate vel ullam voluptatum maxime harum nemo ipsa sequi sapiente assumenda vitae, beatae iste sed veritatis ipsam dicta deserunt.</span>
+<span>Lorem ipsum dolor sit amet consectetur adipisicing elit. Tenetur ad fugit
+    cupiditate vel ullam voluptatum maxime harum nemo ipsa sequi sapiente
+    assumenda vitae, beatae iste sed veritatis ipsam dicta deserunt.</span>

This (obviously) has the disadvantage of making assumptions about the the display property of all elements, but (in my opinion) should handle most cases where undesired wrapping currently occurs.


What is your opinion on this? Is this something you want to try to handle? Should we go with the easy route, or should we try to replicate the (very complicated) logic used for vanilla HTML by Prettier core?

Using with "preprocess"

First of all, thanks for all your effort on building these tools for svelte! I'm really looking forward to be able to auto-format my templates without breaking the style of all svelte related tags.

It's working pretty much okay in simple cases, but it doesn't seem to work whenever my template use a custom css preprocessor like postcss.

Always put <svelte:options> at top of file

I think it would be prettier if the <svelte:options> tag was always at the top of file, before scripts and styles.

Maybe <svelte:head> should also be at the top (but not any of the other <svelte:...> tags)?

svelteAllowShorthand not available on the npm registry

Hi guys!

Although the readme file makes reference to svelteAllowShorthand option,
this option isn't available on the current version published on npm
https://www.npmjs.com/package/prettier-plugin-svelte
which is version 0.7.0 what matches the version on package on the repo

https://github.com/UnwrittenFun/prettier-plugin-svelte/blob/0debb22edc1a1eb49c5925f9f5a133d35ffdf0b7/package.json

The svelteAllowShorthand is already merged into master
https://github.com/UnwrittenFun/prettier-plugin-svelte/blob/0debb22edc1a1eb49c5925f9f5a133d35ffdf0b7/src/options.ts
So we should get a new version..
Can you check what is going on with your CI, maybe there is something wrong stopping to trigger a new version when merging code to master!?

Thanks

Error: Cannot find module 'svelte/compiler' (v 4.2.0)

After update the plugin I got an error "Error: Cannot find module 'svelte/compiler'"
I installed the plugin as a global and as a local lib
Svelte installed only as a local lib

prettier src/Form.svelte              
src/Form.svelte[error] src/Form.svelte: Error: Cannot find module 'svelte/compiler'
[error]     at Function.Module._resolveFilename (module.js:547:15)
[error]     at Function.Module._load (module.js:474:25)
[error]     at Module.require (module.js:596:17)
[error]     at require (internal/module.js:11:18)
[error]     at Object.parse (/home/jungle/.nvm/versions/node/v8.11.1/lib/node_modules/prettier-plugin-svelte/plugin.js:479:20)
[error]     at Object.parse$2 [as parse] (/home/jungle/.nvm/versions/node/v8.11.1/lib/node_modules/prettier/bin-prettier.js:10635:19)
[error]     at coreFormat (/home/jungle/.nvm/versions/node/v8.11.1/lib/node_modules/prettier/bin-prettier.js:13844:23)
[error]     at format (/home/jungle/.nvm/versions/node/v8.11.1/lib/node_modules/prettier/bin-prettier.js:14103:73)
[error]     at formatWithCursor (/home/jungle/.nvm/versions/node/v8.11.1/lib/node_modules/prettier/bin-prettier.js:14119:12)
[error]     at Object.formatWithCursor (/home/jungle/.nvm/versions/node/v8.11.1/lib/node_modules/prettier/bin-prettier.js:42520:15)

Use an actual HTML parser: unexpected behavior around nested `<style>` / `script` tags

Obligatory https://stackoverflow.com/a/1732454/1422124

Took me a while to track this down, because prettier was also swallowing the error message (I'll investigate and open an issue in the appropriate repo).

Essentially the offending code I had was something like this (adapted from https://github.com/rmariuzzo/react-new-window/blob/2417b08352f34f193cc5e69524379fb70ccecf5b/src/NewWindow.js#L195 for svelte):

<script>
  Array.from(document.styleSheets).forEach(styleSheet => {
    // For <style> elements
    let rules;
    try {
      rules = styleSheet.cssRules;
    } catch (err) {
      console.error(err);
    }
    if (rules) {
      //...
    } else if (styleSheet.href) {
      // for <link> elements loading CSS from a URL
      ...
    }
  });
</script>

<style>...</style>

<div>...</div>

The comment For <style> elements inside the JavaScript causes the regex based parser to think it's a style tag.

Sure it's an edge case, but it might be worth considering switching to an actual HTML parser. Maybe svelte core can be imported into this plugin? I'm sure they're handling this already.

Thanks for the plugin by the way!

Error when including values in props

If I include || '' in the props, I get an error; without that, the file is formatted correctly.

Input:

<div class="account" >
  <div class="accounttitle" >
    <p >Account</p>
      <DynamicTooltip content={$t(message) || ''} >
        <Icon icon={{ name: 'info_outline' }}  / >
      </DynamicTooltip >
  </div >
</div >
 
<script>
  /* JavaScript goes here... */
</script>

Output:

SyntaxError: Unexpected closing tag "DynamicTooltip". It may happen when the tag has already been closed by another tag. For more info see https://www.w3.org/TR/html5/syntax.html#closing-elements-that-have-implied-end-tags (6:7)

  4 |       <DynamicTooltip content={$t(message) || ''}>
  5 |         <Icon icon={{ name: 'info_outline' }} />
> 6 |       </DynamicTooltip>
    |       ^
  7 |   </div>
  8 | </div>
  9 |  

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.