Expanding code lines beyond 80 characters in Visual Studio Code with TSLint integration

I am utilizing TypeScript alongside TSLint and Prettier within Visual Studio Code for developing a React Native App.

Despite my efforts to set up my editor to automatically wrap the code per line at 100 characters, it consistently reverts back to 80 characters after saving.

Below are the modifications I made:

"prettier.tslintIntegration": true,
"prettier.printWidth": 100,
"editor.renderIndentGuides": true,
"editor.rulers": [100],
"editor.wordWrapColumn": 100,
"editor.formatOnSave": true

Additionally, here is my tslint.json configuration:

{
  "extends": ["tslint:recommended", "tslint-react", "tslint-config-prettier"],
  "rules": {
    // "jsx-no-lambda": false,
    "member-access": false,
    "interface-name": false,
    "max-line-length": [true, 100]
  }
}

Despite configuring everything as mentioned above, my code keeps wrapping around 80 characters. How can this be resolved?

If a line exceeds 100 characters, a linting error appears, indicating that the tslint.json setting is functioning properly.

As an additional note, below are the complete VSCode settings in case any elements were overlooked:

{
  "telemetry.enableTelemetry": false,
  "workbench.colorTheme": "One Dark Pro",
  "workbench.iconTheme": "vscode-icons",
  "window.zoomLevel": 0,
  "prettier.eslintIntegration": true,
  "prettier.tslintIntegration": true,
  "prettier.printWidth": 100,
  "editor.renderIndentGuides": true,
  "editor.rulers": [100],
  "[javascript]": {
    "editor.tabSize": 2
  },
  "[typescript]": {
    "editor.tabSize": 2
  },
  "[typescriptreact]": {
    "editor.tabSize": 2
  },
  "[json]": {
    "editor.tabSize": 2
  },
  "workbench.colorCustomizations": {
    // "statusBar.background": "#272b33",
    // "panel.background": "#30353f",
    // "sideBar.background": "#2a2b33",
    "editor.background": "#2c313a"
  },
  "todohighlight.keywords": [
    {
      "text": "DEBUG:",
      "color": "#fff",
      "backgroundColor": "limegreen",
      "overviewRulerColor": "grey"
    },
    {
      "text": "NOTE:",
      "color": "#fff",
      "backgroundColor": "mediumslateblue",
      "overviewRulerColor": "grey"
    },
    {
      "text": "REVIEW:",
      "color": "#fff",
      "backgroundColor": "dodgerblue",
      "overviewRulerColor": "grey"
    },
    {
      "text": "XXX:",
      "color": "#fff",
      "backgroundColor": "orangered",
      "overviewRulerColor": "grey"
    }
  ],
  "editor.wordWrapColumn": 100,
  "editor.formatOnSave": true
}

Answer №1

If you're looking to enable word wrapping in your code editor, consider these two settings:

"editor.wordWrap": "wordWrapColumn",
"editor.wordWrapColumn": 100

It appears that the setting "editor.wordWrap" may be missing from your configuration. In Visual Studio Code (vscode), this setting determines the wrapping policy: "wordWrapColumn" instructs it to wrap at the specified column defined by "editor.wordWrapColumn".

You could also experiment with "editor.wordWrap": "bounded", which will adhere to the "wordWrapColumn" value but also wrap based on the viewport width.

Update: Following our conversation in the comments, it seems that Prettier may not be respecting the "printWidth" settings for some reason. This could be due to one of the following:

  1. A potential issue as outlined here: https://github.com/prettier/prettier-vscode/issues/595
  2. The sequence in which configuration options are prioritized, detailed here: https://github.com/prettier/prettier-vscode#prettiers-settings. It looks for Prettier config files first, followed by .editorconfig files, and then vscode settings.

To address this, you might try explicitly defining this setting in either your project's Prettier config file or an .editorconfig file to see if the vscode plugin responds accordingly.

Answer №2

After some trial and error, I discovered a simple solution that worked perfectly for me. First, navigate to your settings and search for the parameter called Print Width. Adjust the value of Prettier: Print Width to fit your specific requirements - the default is 80, but I personally changed it to 150 with great success. Additionally, make sure to include the following lines in your settings.json file:

"editor.wordWrap": "wordWrapColumn",
"editor.wordWrapColumn": 150,
"prettier.printWidth": 150

https://i.sstatic.net/HjpLV.png

Answer №3

Locate the .prettierrc.js file in your project directory or create it if it doesn't exist, then include the printWidth parameter as demonstrated below

module.exports = {
  bracketSpacing: false,
  jsxBracketSameLine: true,
  singleQuote: true,
  trailingComma: 'all',
  arrowParens: 'avoid',
  printWidth: 150, // <== add this
};

Learn more about configuration options here

Answer №4

After installing prettier, all I needed to do was add the following line to resolve the issue:

"prettier.printWidth": 120,

Typically, wrap lengths are set at either 80 or 120, but some prefer 150.

You can include the above settings in either of the following locations:

Project workspace settings:

  • .vscode\settings.json

User settings:

  • %UserProfile%\AppData\Roaming\Code\User\settings.json

The paths stated above are for Windows OS, but similar ones will apply to other operating systems as well.

Answer №5

To ensure proper formatting in your tslint.json file, consider including the printWidth option within the Prettier configuration section:

"rules": {
    "prettier": [
        true,
        {
            "printWidth": 100
        }
    ],

Don't forget to follow the advice of vaglignatev and install the tslint-config-prettier package.

Answer №6

Encountering a similar problem, I found that the .editorconfig file was taking precedence over my prettier settings. To resolve this, I simply included the line max_line_length = 100

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When using Protractor with Typescript, you may encounter the error message "Failed: Cannot read property 'sendKeys' of undefined"

Having trouble creating Protractor JS spec files using TypeScript? Running into an error with the converted spec files? Error Message: Failed - calculator_1.calculator.prototype.getResult is not a function Check out the TypeScript files below: calculato ...

What is the proper way to reference a computed symbol that has been inherited as a function in an extended class

As a newcomer to Typescript, my understanding of the code might be lacking. I am currently working with the Klasa framework, which is built on top of Discord bot framework using Discord.js. The framework recently introduced plugin functionality and there a ...

Using createContext in React.tsx to pass the state through useState

There is a context called Transaction that accepts an object and a function as parameters. In the AppProvider component, the Transaction.Provider is returned. The following code snippet is from the GlobalState.tsx file: import { createContext, useState } f ...

The production build is encountering an issue with a type error stating that the property 'companies' does not exist on the 'PrismaClient' type, while the local build is successful

Currently, I am working on a nextjs project hosted on Vercel, utilizing TypeScript and Prisma. Here are the versions I am using: "next": "13.0.3" "typescript": "4.9.3" "prisma": "^4.6.1" My local build is successful, but I am encountering a failure on Ve ...

Tips for accessing the return value from a method outside of its containing function

Having recently started using Angular, I'm encountering an issue with retrieving a return value from a function that I have implemented within another one. private validateKeyterm(): boolean { const val = this.form.value.term; if ...

Transcompiling TypeScript for Node.js

I'm in the process of developing a Node project using Typescript, and I've configured the target option to es6 in my tsconfig.json file. Although Node version 8 does support the async/await syntax, Typescript automatically converts it to a gener ...

Verify that each interface in an array includes all of its respective fields - Angular 8

I've recently created a collection of typed interfaces, each with optional fields. I'm wondering if there is an efficient method to verify that all interfaces in the array have their fields filled. Here's the interface I'm working wit ...

Exploring a JSON Object in TypeScript: A Step-by-Step Guide

I am currently utilizing Angular 7 and have a query that returns JSON data with a specific format: [ { "text": "test 1", "value": "1", "nbr": "1", "children": [ { "text": "test 1_1", ...

Exploring the Uses of SystemJS with TypeScript Loader

Can someone help clarify something about this TypeScript plugin for SystemJS? https://github.com/frankwallis/plugin-typescript/ Here is what the plugin does: This SystemJS plugin allows you to import TypeScript files directly and have them compiled in ...

Unveiling the method of retrieving a targeted value from JWT in React

I'm struggling to retrieve a specific value from my JWT token in React. I am using the react-jwt library to decode the token, and when I log it, I receive this output: Object { userId: "850dff98-54fb-4059-9e95-e44f5c30be0f", iat: 1698866016 ...

Issue with sx prop type error found in the TabPanel component of MUI v5

My first time using MUI with TypeScript has hit a roadblock with the new sx prop. Check out the error displayed by TypeScript in the screenshot linked below: https://i.sstatic.net/JYDTX.png Interestingly, the error only pops up on the TabPanel Component, ...

Out of nowhere, an error popped up indicating an undefined Python version in my Jupyter Notebook within Visual Studio Code

Out of nowhere, my vscode is showing an undefined kernel error. I am able to execute my code, but as soon as I attempt to run it, the undefined kernel error message pops up leading me to this link (https://github.com/microsoft/vscode-jupyter/wiki/Using-un ...

Attempting to simulate the behavior of Angular2 Token during testing

Currently, I am working on obtaining a token that is required for API authentication to retrieve a list. My approach begins with importing the angular2-token library: import { Angular2TokenService } from 'angular2-token'; After this, I include ...

The specified file ngx-extended-pdf-viewer/assets/pdf.js cannot be found

I have integrated the ngx-extended-pdf-viewer package in my Angular application using npm to enable the display of PDF content. According to the setup instructions, I have added the following configuration in my angular.json file: "assets": [ ...

Integrating a cutting-edge feature into your Angular project

After incorporating a new Service into an established Angular project using the command: $ ng generate service utils/new I decided to transfer certain methods from AppService to NewService. Both services have identical constructors: @Injectable({ provi ...

Guide on troubleshooting Node TypeScript in Visual Studio Code when the JavaScript source is stored in a separate directory

When using Visual Studio Code, I am able to debug and step through the TypeScript source code of Main.ts. This is possible as long as the JavaScript and map files are located in the same folder as the TypeScript source. This setup works well in this struc ...

Invalid Type Property - Request and Response Express Types

When I try to utilize the Request or Response types in this manner: app.use('*', (req: Request, res: Response, next: NextFunction) => { res.set('Cache-Control', 'no-store'); const requestId: string = req.headers[&a ...

How can we retrieve the target element for an 'onSelectionChange' DOM event in Angular 6?

When using Angular 6, I want to retrieve the "formControlName" of the corresponding element whenever the selection changes. HTML <mat-form-field *ngIf="dispatchAdviceChildForAdd._isEditMode" class="mat-form-field-fluid"> <mat-select ...

Issue with module import in Next.js: "<module name>__WEBPACK_IMPORTED_MODULE_1___default(...).<function name>" Are We Making a Mistake?

I have a basic Next.js project with TypeScript that I have enhanced by adding Jimp. I am utilizing the experimental app directory in my configuration. This is how my next.config.js file looks: /** @type {import('next').NextConfig} */ const nextC ...

When creating utility classes, is it beneficial to offer a non-mutable API to facilitate their integration with frameworks such as React?

Currently, I am working on enhancing the functionality of my DateWithoutTime class. As part of this process, private fields within the class need to be updated by public methods. this.state.dateWithoutTimeInstance.shiftBySpecificDaysCount({ daysCount: 5, ...