Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Decorators problem for Angular project. #12

Closed
temofey1989 opened this issue Dec 2, 2020 · 10 comments · Fixed by #35 or #88
Closed

Decorators problem for Angular project. #12

temofey1989 opened this issue Dec 2, 2020 · 10 comments · Fixed by #35 or #88
Labels
bug Something isn't working investigation

Comments

@temofey1989
Copy link

Hello,

I tried to use the plugin in the Angular project and got this error:

> prettier --write src/app/app.component.ts --config ./.prettierrc
src\app\app.component.ts
[error] src\app\app.component.ts: SyntaxError: This experimental syntax requires enabling one of the following parser plugin(s): 'decorators-legacy, decorators' (5:0)
[error]    1 | import { isEmpty } from "lodash-es";
[error]    2 | 
[error]    3 | import { Component } from "@angular/core";
[error]    4 | 
[error]    5 | @Component({
[error]    6 |   selector: "app-root",
[error]    7 |   templateUrl: "./app.component.html",
[error]    8 |   styleUrls: ["./app.component.css"]
[error]    9 | })
[error]   10 | export class AppComponent {
[error]   11 |   title = "ng-prettier";
[error]   12 | 
[error]   13 |   get text(): string {
[error]   14 |     return isEmpty(this.title) ? "" : this.title;
[error]   15 |   }
[error]   16 | }
[error]   17 | 
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! ng-prettier@0.0.0 format: `prettier --write src/app/app.component.ts --config ./.prettierrc`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the ng-prettier@0.0.0 format script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

I use:

  • Prettier: 2.2.0
  • Angular: 11.0.2
  • Typescript: 4.0.5
  • Plugin version: 1.3.0

What am I doing wrong?
Is there any workaround?

Thanks a lot.

NOTE: No problem with React.

@byara
Copy link
Collaborator

byara commented Dec 6, 2020

@temofey1989 What is your prettier config in .prettierrc?

Just a guess would be that you are not defining the parser option as angular in the .prettierrc.

@temofey1989
Copy link
Author

temofey1989 commented Dec 8, 2020

@byara, you are right.
After adding "parser": "angular" to the .prettierrc the command executed with no error.
This is my .prettierrc file:

{
  "tabWidth": 2,
  "printWidth": 120,
  "singleQuote": false,
  "useTabs": false,
  "bracketSpacing": true,
  "semi": true,
  "trailingComma": "none",
  "importOrder": [
    "^@angular/(.*)$",
    "^rxjs(.*)$",
    "^lodash(.*)$",
    "^[./]"
  ],
  "importOrderSeparation": true,
  "parser": "angular"
}

Nevertheless, now I have another problem...
Formatted code looks like this:

import { isEmpty } from "lodash-es"; import { Component } from "@angular/core"; @Component({ selector: "app-root",
templateUrl: "./app.component.html", styleUrls: ["./app.component.css"] }) export class AppComponent { title =
"ng-prettier"; get text(): string { return isEmpty(this.title) ? "" : this.title; } }

This looks not really prettiery... 😄

@szaboge
Copy link

szaboge commented Dec 9, 2020

I have the same problem, now all the files look minimized.

{
  parser: 'angular',
  printWidth: 120,
  tabWidth: 2,
  useTabs: false,
  semi: true,
  singleQuote: true,
  trailingComma: 'all',
  bracketSpacing: false,
  jsxBracketSameLine: false,
  arrowParens: 'avoid',
  rangeStart: 0,
  rangeEnd: Infinity,
  requirePragma: false,
  insertPragma: false,
  proseWrap: 'preserve',
  importOrder: ['^rxjs/(.*)$', '^@angular/(.*)$', '^[./]'],
  importOrderSeparation: true,
}

@byara byara added bug Something isn't working investigation labels Dec 9, 2020
@byara
Copy link
Collaborator

byara commented Dec 9, 2020

@temofey1989 @szaboge could you also please provide your babel config?

@szaboge
Copy link

szaboge commented Dec 10, 2020

@byara I don't have custom babel config, I use default Angular CLI for the build.
Typescript compiler config:

{
    "allowSyntheticDefaultImports": true,
    "allowUnreachableCode": true,
    "baseUrl": "src",
    "declaration": false,
    "downlevelIteration": true,
    "emitDecoratorMetadata": true,
    "esModuleInterop": true,
    "experimentalDecorators": true,
    "importHelpers": true,
    "lib": ["es5", "es6", "es7", "dom"],
    "module": "es2020",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "noImplicitAny": false,
    "noUnusedLocals": true,
    "outDir": "build",
    "pretty": true,
    "removeComments": false,
    "sourceMap": false,
    "strictNullChecks": false,
    "target": "es2015",
    "types": ["node", "jest"]
  }

@ghost
Copy link

ghost commented Dec 11, 2020

The angular formatter is only used for angular HTML, as suggested by the prettier docs:

  • "angular" (same parser as "html", but also formats angular-specific syntax via angular-estree-parser)

https://prettier.io/docs/en/options.html#parser

You instead should be using typescript as the typescript language hasn't been extended by Angular.

However, doing that returns you to the original error about experimental features. We discovered that changing this line
https://github.com/trivago/prettier-plugin-sort-imports/blob/master/src/preprocessor.ts#L15

        plugins: ['typescript', 'jsx'],

to

        plugins: ['typescript', 'jsx', ['decorators', {'decoratorsBeforeExport': true}], 'classProperties'],

and with the following babel config (in babel.config.json):

{
    "presets": ["@babel/preset-typescript"],
    "plugins": [
        ["@babel/plugin-proposal-decorators", { "legacy": true}],
        ["@babel/plugin-proposal-class-properties", {"loose": true}]
    ]
}

seemed to solve the issues with the unsupported syntax, but then ran into issues with the comments being stripped from files as #13 hasn't made it into a release yet.

byara pushed a commit that referenced this issue Dec 15, 2020
byara pushed a commit that referenced this issue Dec 15, 2020
byara pushed a commit that referenced this issue Mar 4, 2021
byara pushed a commit that referenced this issue Mar 4, 2021
byara pushed a commit that referenced this issue Mar 4, 2021
byara pushed a commit that referenced this issue Mar 5, 2021
byara pushed a commit that referenced this issue Mar 5, 2021
@byara byara linked a pull request Mar 13, 2021 that will close this issue
ayusharma pushed a commit that referenced this issue Mar 15, 2021
* [#12] handle babel config better

* [#12] simplify parsers

* abstract getBabelConf out

* Pass plugins through rc file

* implement getParserPlugins

* add parser names as constants

* one function def per file, separate constants and types, clean up

* clean yp flow types, constants and getParserPlugins return type

* pass util functions directly

* add test for new API

* add LiteralUnion for parser types

* Clean up types

* update depencencies except babel

* update babel

* change getBabelConf name, add comment to tsPlugin as to why we are adding them by default

* remove unused babel config

* update types for experimentalBabelParserPluginsList as ParserPlugin

* update readme

Co-authored-by: Behrang Yarahmadi <behrang.yarahmdi@trivago.com>
@byara
Copy link
Collaborator

byara commented Mar 16, 2021

With the release of v2.0.1, this should be fixed.
Either prettier will figure out the syntax correctly, or you can use experimentalBabelParserPluginsList in your .prettierrc to pass the correct parser name.

If there was still problems, you can of course re-open this issue.

@saaryab
Copy link
Contributor

saaryab commented Oct 7, 2021

Update: I posted this reply in a new issue: #86

Hi @byara (or whoever is working on this now),

Thanks for making and maintaining this plugin!

experimentalBabelParserPluginsList allows adding custom babel parser plugins, but it does not allow sending plugin options.

For example, @ShigotoMitame was using the decorators plugin with the following options:

plugins: ['typescript', 'jsx', ['decorators', {'decoratorsBeforeExport': true}], 'classProperties'],

It seems like the preprocessor.js code should allow any type of babel plugin, both a string and an array of [PLUGIN_NAME: string, PLUGIN_OPTIONS: object], but when adding a plugin with options I get the following error:

$ /home/.../project/node_modules/.bin/prettier -w .
[error] Invalid experimentalBabelParserPluginsList value. Expected an array of a string, but received [["decorators", { decoratorsBeforeExport: true }]].
error Command failed with exit code 1.

When adding these options directly in preprocessor.js like @ShigotoMitame did everything works as expected so it looks liek this is a validation issue caused by prettier's options which don't seem to support any complex values:

 * @property {'int' | 'boolean' | 'choice' | 'path'} type

https://github.com/prettier/prettier/blob/5909f5b3f191a0a32f759e1f4378477d3b90e28e/src/main/core-options.js#L17

As a work around I was wondering if you would consider supporting taking the plugins directly from a babelrc file, or at least allowing JSON in the experimentalBabelParserPluginsList array to support plugins with options.

@ichepurnoy
Copy link

As of now, with prettier-plugin-sort-imports v3.2.0, I was able to solve it with the following config:

module.exports = {
  trailingComma: 'all',
  useTabs: false,
  tabWidth: 2,
  semi: true,
  singleQuote: true,
  bracketSpacing: true,
  importOrder: ['^@angular/(.*)$', '^(.*)ngrx(.*)$', '^(.*)module(.*)$', '^(.*)service(.*)$', '^(.*)guard(.*)$', '^(.*)pipe(.*)$', '^rxjs/(.*)$', '^[./]'],
  importOrderSeparation: true,
  importOrderSortSpecifiers: true,
  importOrderParserPlugins: ['typescript', "classProperties", "[\"decorators\", { \"decoratorsBeforeExport\": true }]"],
  parser: 'typescript',
  printWidth: 140,
};

Escaped double quotes inside importOrderParserPlugins are important, I tried changing them to single qoutes and failed.

@hminnnn
Copy link

hminnnn commented Aug 17, 2022

I've got this error with prettier formatting when using sequelize typescript syntax

["ERROR" - 11:58:19 AM] Error formatting document.
["ERROR" - 11:58:19 AM] This experimental syntax requires enabling one of the following parser plugin(s): 'decorators-legacy, decorators' (25:0)

and adding this to .prettierrc solved my problem

"importOrderParserPlugins": ["typescript", "decorators-legacy"]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working investigation
Projects
None yet
6 participants