Joel  Hawkins

Joel Hawkins

1587260640

Visual Studio Code: A Power User’s Guide

In this guide, you’ll learn how to take advantage of Visual Studio Code to supercharge your development workflow.

This article is written for beginners who may be using Visual Studio Code for the first time. VS Code, as it’s commonly known, is considered a “lightweight” code editor. In comparison with full integrated development environment (IDE) editors which occupy gigabytes of disk space, VS Code uses less than 200MB when installed.

Despite the “lightweight” term, Visual Studio Code offers a massive number of features which keep increasing and improving with every new update. For this guide, we’ll cover the most popularly used features. Every programmer has their own tool set which they keep updating whenever new workflows are discovered. If you want to learn every tool and feature VS Code has to offer, check out their official documentation. In addition, you may want to keep track of updates for new and improved features.

Prerequisites

In order to follow this guide, you need to be proficient in at least one programming language and framework. You also need to be conversant with versioning your project code with git. You’ll also need to have an account with a remote repository platform such as GitHub. I recommend you setup SSH Keys to connect with your remote repo.

We’ll use a minimal Next.js project to demonstrate VS Code features. If you’re new to this, don’t worry, as the framework and the language used are not the focus for this guide. The skills taught here can be transferred to any language and framework that you’re working with.

A Bit of History

If you’re new to programming, I recommend you start with a simple text editor such as Windows NotePad. It’s the most basic text editor and doesn’t offer any kind of help whatsoever. The main advantage of using it is that it forces you to memorize language syntax and do your own indentation. Once you get comfortable writing code, upgrading to a better text editor such as NotePad++ is the next logical step. It offers a bit of essential coding help with features like syntax colorization, auto indentation and basic autocomplete. It’s important when learning programming not to be overwhelmed with too much information and assistance.

Once you’ve gotten used to having a better coding experience, it’s time to upgrade. Not so long ago, these were the fully integrated development environments on offer:

These platforms provide the complete development workflow, from coding to testing and deployment. They contain tons of useful features such as analyzing code and highlighting errors. They also contain a ton more features that many developers weren’t using, though they were essential for some teams. As a result, these platforms took a lot of disk space and were slow to start up. Many developers preferred using advance text editors such as emacs and vim to write their code in.

Soon, a new crop of platform independent code editors started appearing. They were lightweight and provided many features that were mostly exclusive to IDEs. I’ve listed them below in the order they were released:

Mac developers had access to TextMate which was released in October 2004. The snippets system used by all the above editors originated from TextMate. Having used all of them, I felt that the editor that came after was a significant improvement over the current one. According to a developer survey done by Stack OverFlow in 2019, Visual Studio Code is the most popular code development environment with 50.7% usage. Visual Studio IDE comes second and NotePad++ comes third.

That’s enough history and stats for now. Let’s delve into how to use Visual Studio Code features.

Setup and Updates

Visual Studio Code’s package installer is less than 100MB and consumes less than 200MB when fully installed. When you visit the download page, your OS will automatically be detected and the correct download link will be highlighted.

Updating VS Code is very easy. It displays a notification prompt whenever an update has been released. For Windows users, you’ll have to click on the notification to download and install the latest version. The download process occurs in the background while you’re working. When it’s ready to install, a restart prompt will appear. Clicking this will install the update for you and restart VS Code.

For Ubuntu-based distributions, clicking on the update notification will simply open the website for you to download the latest installer. A much easier way is simply running sudo apt update && sudo apt upgrade -y. This will update all installed Linux packages including Visual Studio Code. The reason this works is because VS Code added its repo to your package repo registry during the initial installation. You can find the repo information on this path: /etc/apt/sources.list.d/vscode.list.

User Interface

Let’s first get acquainted with the user interface:

VS Code user interface

Image source

Visual Studio Code’s user interface is divided into five main areas which you can easily adjust.

  • Activity Bar: allows you to switch between views: explorer, search, version control, debug and extensions.
  • Side Bar: contains the active view.
  • Editor: this is where you edit files and preview markdown files. You can arrange multiple open files side-by-side.
  • Panel: displays different panels: integrated terminal, output panels for debug information, errors and warnings.
  • Status: displays information about the currently opened project and file. Also contains buttons for executing version control actions, and enabling/disabling extension features.

There’s also the top Menu Bar where you can access the editor’s menu system. For Linux users, the default integrated terminal will probably be the Bash shell. For Windows users, it’s PowerShell. Fortunately, there’s a shell selector located inside the terminal dropdown that will allow you to choose a different shell. If installed, you can choose any of the following:

  • Command Prompt
  • PowerShell
  • PowerShell Core
  • Git Bash
  • WSL Bash

Working with Projects

Unlike full IDEs, Visual Studio Code doesn’t provide project creation or offer project templates in the traditional way. It simply works with folders. On my Linux development machine, I’m using the following folder pattern to store and manage my projects:

/home/{username}/Projects/{company-name}/{repo-provider}/{project-name}

The Projects folder is what I refer to as to the workspace. As a freelance writer and developer, I separate projects based on which company I’m working for, and which repo I’m using. For personal projects, I store them under my own fictitious “company name”. For projects that I experiment with for learning purposes, and which I don’t intend to keep for long, I’ll just use a name such as play or tuts as a substitute for {repo-provider}.

If you’d like to create a new project and open it in VS Code, you can use the following steps. Open a terminal and execute the following commands:

$ mkdir vscode-demo
$ cd vscode-demo
# Launch Visual Studio Code
$ code .

You can also do this in File Explorer. When you access the mouse context menu, you should be able to open any folder in VS Code.

If you want to create a new project linked to a remote repo, it’s easier creating one on the repo site — for example, GitHub or BitBucket.

GitHub create project

Take note of all the fields that have been filled in and selected. Next, go to the terminal and execute the following:

# Navigate to workspace/company/repo folder
$ cd Projects/sitepoint/github/

# Clone the project to your machine
$ git clone git@github.com:{insert-username-here}/vscode-nextjs-demo.git

# Open project in VS Code
$ cd vscode-nextjs-demo
$ code .

Once the editor is up and running, you can launch the integrated terminal using the keyboard shortcut Ctrl+~ (tilde key). Use the following commands to generate package.json and install packages:

# Generate `package.json` file with default settings
$ npm init -y

# Install package dependencies
$ npm install next react react-dom

Next, open package.json and replace the scripts section with this:

"scripts": {
  "dev": "next",
  "build": "next build",
  "start": "next start"
}

The entire Visual Studio Code window should look like this:

VS Code run script

Before we look at the next section, I’d like to mention that VS Code also supports the concept of multi-root workspaces. If you’re working with related projects — front-end, back-end, docs etc. — you can manage them all in a single workspace inside one editor. This will make it easier to keep your source code and documentation in sync.

Version Control with Git

Visual Studio Code comes built-in with Git source control manager. It provides a UI interface where you can stage, commit, create new branches and switch to existing ones. Let’s commit the changes we just did in our project. On the Activity bar, open the Source Control Panel and locate the Stage All Changes plus button as shown below.

VS Code source control

Click on it. Next, enter the commit message “Installed next.js dependencies”, then click the Commit button at the top. It has the checkmark icon. This will commit the new changes. If you look at the status located at the bottom, you’ll see various status icons at the left-hand corner. The 0 ↓ means there’s nothing to pull from the remote repo. The 1 ↑ means you’ve got one commit you need to push to your remote repo. Clicking on it will display a prompt on the action that will take place. Click OK to pull and push your code. This should sync up your local repo with the remote repo.

To create a new branch or switch to an existing branch, just click the branch name master on the status bar, left bottom corner. This will pop up a branch panel for you to take an action.

VS Code branch actions

Do check out the following extensions for an even better experience with Git:

Support for a different type of SCM, such as SVN, can be added via installing the relevant SCM extension from the marketplace.

Creating and Running Code

On the Activity Bar, head back to the Explorer Panel and use the New Folder button to create the folder pages at the root of the project. Select this folder and use the New File button to create the file pages/index.js. Copy the following code:

function HomePage() {
  return <div>Welcome to Next.js!</div>;
}

export default HomePage;

With the Explorer Panel, you should see a section called NPM Scripts. Expand on this and hover over dev. A run button (play icon) will appear next to it. Click on it and this will launch a Next.js dev server inside the Integrated Terminal.

VS Code run script

It should take a few seconds to spin up. Use Ctrl + Click on the URL http://localhost:3000 to open it in your browser. The page should open successfully displaying the “Welcome” message. In the next section, we’ll look at how we can change Visual Studio Code preferences.

User and Workspace Settings

To access VS Code preference settings, use the shortcut key Ctrl + ,. You can also access it via the menu command like this:

  • On Windows/Linux – File > Preferences > Settings
  • On macOS – Code > Preferences > Settings

By default, a Settings editor graphical interface should appear. It helps users make changes to preferences easily, as there are thousands of editable settings that are available. The Settings editor provides user friendly names and description for what each setting does. In addition, related settings have been grouped together and there’s a search bar for locating a specific setting.

VS Code settings panel

When changing settings using the editor, pay attention to the active scope at the top. Take note that not all settings can be configured via the graphical interface. For that, you have to edit the file settings.json directly. As you scroll down the Settings editor, you’ll come across a shortcut that will take you to this file.

There are two different scopes that Visual Studio Code settings are classified under:

  • User Settings: Settings are stored under user account. They will take effect on all projects your work on.
  • Workspace: Settings are stored within project or workspace folder. They will apply only in that specific project.

Depending on your platform, you can locate VS Code’s user setting in the following locations:

  • Windows: %APPDATA%\Code\User\settings.json
  • macOS: $HOME/Library/Application Support/Code/User/settings.json
  • Linux: $HOME/.config/Code/User/settings.json

For Workspace, simply create a folder .vscode at the root of your project. Then create the file settings.json inside this folder. If working with the Settings editor panel, it will do this for you automatically when you change settings under the Workspace scope. Here’s a subset of the global settings I prefer to work with:

{
  "editor.minimap.enabled": false,
  "window.openFoldersInNewWindow": "on",
  "diffEditor.ignoreTrimWhitespace": false,
  "files.trimTrailingWhitespace": true,
  "javascript.updateImportsOnFileMove.enabled": "always",
  "workbench.editor.enablePreview": false,
  "workbench.list.openMode": "doubleClick",
  "window.openFilesInNewWindow": "default",
  "editor.formatOnPaste": true,
  "editor.defaultFormatter": "esbenp.prettierVS Code",
  "editor.formatOnSave": true,
  "editor.tabSize": 2,
  "explorer.confirmDelete": false
}

I tend to work with multiple projects simultaneously, hence the setting window.openFoldersInNewWindow allows me to open new project folders without closing (replacing) the active one. For editor.defaultFormatter, I’ve set it to Prettier, which is an extension I have installed. We’ll discuss this in a later section shortly. Next, let’s look at language associations.

Language Association

I do a lot of projects using React. Lately, most React frameworks generate components use the .js extension instead of .jsx. As a result, formatting and syntax colorization becomes a problem when you start writing JSX code. To fix this, you need to associate .js files with JavaScriptReact. You can easily do this by changing Language Mode via the Ctrl + Shift + P command panel. You can also update settings.json by adding this configuration:

{
  "files.associations": {
    "*.js": "javascriptreact"
  }
}

Next time you open a JS file, it will be treated as a React JSX file. I’ve specified this in my global settings since I often work with React projects. Unfortunately, doing this breaks a built-in feature called Emmet. It’s a popular plugin that helps developers autocomplete HTML and CSS code in a very intuitive way. You can fix this issue by adding the following configuration in settings.json:

{
  "emmet.includeLanguages": {
    "javascript": "javascriptreact"
  }
}

Next time you have trouble activating Emmet for a particular file extension or language, check to see if it can be resolved by adding the language association in emmet.includeLanguages. For more information, check out the official documentation for VS Code Emmet.

Keyboard Shortcuts

So far, we’ve covered two keyboard shortcuts:

  • Ctrl + ,: Open settings
  • Ctrl + Shift + P: Open command palette

The Command Palette provides access to Visual Studio Code’s entire functionality including keyboard shortcuts for common operations. If you install an extension, any manually triggered actions will be listed here. However, for extensions such as Prettier and Beautify, they’ll use the same Format command. Visual Studio Code also has its own built-in formatter plugin. To specify which plugin should execute the action, you need to go to the Settings editor and change the Default Formatter configuration. Here’s an example of how I’ve set it in mine:

{
  "editor.defaultFormatter": "esbenp.prettierVS Code"
}

You can also specify a different formatter for a specific language mode. Here are several more keyboard shortcuts you need to memorize:

  • Ctrl + P will let you navigate to any file or symbol by typing its name
  • Ctrl + Tab will cycle you through the last set of files opened
  • Ctrl + Shift + O will let you navigate to a specific symbol in a file
  • Ctrl + G will let you navigate to a specific line in a file

Here are my favorite commands I use often while writing code:

  • Ctrl + D: press multiple times to select identical keywords. When you start typing, it renames all the selected keywords
  • Ctrl + Shift + Up/Down: Add Cursor above or below in order to edit multiple lines at once
  • Alt + Shift + Click: Add Cursor at multiple locations in order to edit in different sections of code simultaneously
  • Ctrl + J: Add 2 or more lines into one. Works perfectly if you’ve a formatter active as you edit code
  • Ctrl + F: Search for a keyword in current file
  • Ctrl + H: Search and replace in current file
  • Ctrl + Shift + F: Search in all files

If you visit the Menu options, you’ll find shortcut keys for most commands. Personally, I’ve never gotten used to some of the default shortcut keys that come with Visual Studio Code due to using editors such as Atom for a long time. The solution I found was simply to install the Atom Keymap. This allows me to use the shortcut key Ctrl + </kbd> to toggle the Side Bar. If you’d like to edit the keyboard bindings yourself, simply go to the menu under File > Preferences > Keyboard Shortcuts. (Code > Preferences > Keyboard Shortcuts on macOS).

keyboard binding editor

Code Editor Features

In this section, we’ll quickly look into the various developer-friendly features Visual Studio Code provides to help you write faster, cleaner and more maintainable code.

Intellisense

This is a popular feature also known as “code completion” or autocomplete. Out of the box, VS Code provides Intellisense for:

  • JavaScript, TypeScript
  • HTML
  • CSS, SCSS and Less

As you type your code, a pop with a list of possible options will appear. The more you type, the shorter the list gets. You can press Enter or Tab once your intended keyword is highlighted to autocomplete your code. Pressing Esc will remove the popup. Inserting a . at the end of a keyword or pressing Ctrl + space bar will trigger the IntelliSense popup to appear.

IntelliSense demo

If you’re working with a language that is not supported out of the box, you can install a language extension from the marketplace to activate IntelliSense for your desired programming language. Check out the official docs to learn more on how you can customize IntelliSense.

Snippets

Typing repetitive code such as if statements, for loops and component declaration can be a bit tiring. You might find yourself copying and pasting code to work faster. Fortunately, Visual Studio Code offers a feature called Snippets, which are simply templates of code. For example, instead of typing console.log, just type log and IntelliSense will prompt to insert the snippet for you.

There are many snippets you can access as long as you’ve memorized the shorthand or keyword that triggers snippet insertion. Since you’re new to this, you can access a list of all snippets available via Command Palette > Insert Snippets:

insert snippets

Scroll up and down to view the entire list. Take note that most snippets have tabstops that allow you to replace the relevant sections of code when you insert them. You can find more snippet extensions in the marketplace. You can also create your own. This article shows you how to do both. You can check out the official docs for more information on how to define your own snippets.

Formatting

Often when typing or pasting code from different sources, we tend to mix coding styles. For example:

  • indenting with space vs tabs
  • ending with semicolon
  • double quotes or single quotes

Formatting is important, as it makes the code readable. However, it can be time consuming when you come across large sections of unformatted code. Luckily, Visual Studio Code can perform formatting for you with a single command. You can execute the formatting command via the Command Palette. Visual Studio Code supports formatting for the following languages out of the box:

  • JavaScript
  • TypeScript
  • JSON
  • HTML

You can customize Visual Studio Code’s formatting behavior by changing the following settings to true or false:

  • editor.formatOnType: format the line after typing
  • editor.formatOnSave: format a file on save
  • editor.formatOnPaste: format the pasted content

However, the built-in formatters may not conform to your style of coding. If you’re working with frameworks such as React, Vue or Angular, you’ll find that the built-in formatters tend to mess up your code. You can fix this by disabling formatting for a specific language:

"html.format.enable": false

However, the best solution is to install a formatter extension from the marketplace. My favorite is [Prettier](https://marketplace.visualstudio.com/items?itemName=esbenp.prettierVS Code), as it supports a huge number of languages including:

  • Flow · JSX · JSON
  • CSS · SCSS · Less
  • Vue · Angular
  • GraphQL · Markdown · YAML

After installing it, you’ll need to set it as the default formatter:

{
  "editor.defaultFormatter": "esbenp.prettierVS Code",
  "&lsqb;javascript&rsqb;": {
    "editor.defaultFormatter": "esbenp.prettierVS Code"
  }
}

It’s also recommended you install prettier package locally as a dev dependency:

npm install prettier -D --save-exact

The default formatting options Prettier enforces may work out for you. If not, you can customize by creating a .prettierrc configuration file either at the root of your project or in your home directory. You can place your custom formatting rules here. Here’s an example:

{
  "trailingComma": "all",
  "tabWidth": 2,
  "semi": false,
  "singleQuote": true
}

Feel free to check out other formatting extensions. However, you’ll find Prettier to be the most popular.

Linting

A Lint, or Linter is a tool that analyzes your code and checks for syntax errors, styling issues, calls to undeclared variables, usage of deprecated functions, misuse of scope and many other issues. Visual Studio Code doesn’t come shipped in with any Linter. However, it does make it easy setting up one for the programming language you’re using. For example, if you’re working on new Python project, you’ll get a prompt to install one for you. You can also open the Command Palette (Ctrl + Shift + P) and select the Python: Select Linter command.

For JavaScript, you’ll need to install an extension such as ESLint which is the most popular. This extension requires you to install ESLint as a dev dependency. You may also need one or more ESLint plugins that will help you lint the coding style and framework you’re using. You can check out our guide on how to configure ESLint. There are also other linter tools you can check out. My recommendation is to go with ESLint as it’s easier to configure and supports more JavaScript styles and frameworks.

Once you’ve set up the linting tool, VS Code will automatically lint your code every time you save the file. You should also update your package.json scripts to include a command for running the lint tool.

Debugging

If you use print statements to debug, you should cease and desist as there’s a better way to debug your code. With VS Code, you can set breakpoints and inspect variables while your code is running.

Image source

Check out our guide on debugging JavaScript projects with VS Code and Chrome Debugger for step-by-step instructions on how to debug your code.

Summary

We’ve now come to the end of the guide. As noted earlier, the information here will help you jump start your way into improving your coding workflow with Visual Studio Code. I recommend you check out our top 10 must-have extensions for VS Code. While most VS Code tools are easy to learn and integrate into your workflow, others need some time to figure out and get used to. Nevertheless, mastering VS Code features will make you an efficient and better software developer.

If you want to reach the absolute peak of productive performance with Visual Studio Code, check out Visual Studio Code: End-to-End Editing and Debugging Tools for Web Developers. It’s a fantastic book from Wiley that you can read online (or off!) in our Premium library.

#vscode #programming

What is GEEK

Buddha Community

Visual Studio Code: A Power User’s Guide

COMO USAR e trabalhar com Code Review no Visual Studio Code

Não é todo programador que gosta de compartilhar o seu trabalho ou até mesmo receber feedbacks de como o seu código foi escrito, mas o Code Review é cada vez mais comum em empresas do mundo todo.

Conheça uma extensão para Visual Studio Code e comece a trabalhar com Code Review em seu próximo projeto. Essa é a sua chance de saber COMO USAR e trabalhar com Code Review no Visual Studio Code.

#visual studio code #code review #visual studio #code

Brain  Crist

Brain Crist

1597032000

User Snippets (Code Shortcuts) in Visual Studio Code

Hello, my friends and fellow developers, this video is all about User Snippets. That means the Snippets (Code Shortcuts) that you can make for yourself. It is a really amazing feature. I hope you like this video

Let me know in the comments below if you want more Visual Studio Code videos or any other videos. And like the video, if you like it.

#visual studio code #visual studio #code

Brain  Crist

Brain Crist

1596975120

Writing Visual Studio Extensions with Mads - Episode 1: Item Templates

Join Mads Kristensen from the Visual Studio team each week as he builds extensions for Visual Studio live!

#visual studio code #visual studio #code #microsoft #visual studio extensions

Emilie  Okumu

Emilie Okumu

1621046940

08 Visual Studio Code - power of breadcrumbs in vscode

See the power of Breadcrumbs to switch to anywhere in project

Remove every clutter from your #vscode to make a minimal screen

#code #visual studio #visual studio code

Mike  Kozey

Mike Kozey

1656151740

Test_cov_console: Flutter Console Coverage Test

Flutter Console Coverage Test

This small dart tools is used to generate Flutter Coverage Test report to console

How to install

Add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dev_dependencies:
  test_cov_console: ^0.2.2

How to run

run the following command to make sure all flutter library is up-to-date

flutter pub get
Running "flutter pub get" in coverage...                            0.5s

run the following command to generate lcov.info on coverage directory

flutter test --coverage
00:02 +1: All tests passed!

run the tool to generate report from lcov.info

flutter pub run test_cov_console
---------------------------------------------|---------|---------|---------|-------------------|
File                                         |% Branch | % Funcs | % Lines | Uncovered Line #s |
---------------------------------------------|---------|---------|---------|-------------------|
lib/src/                                     |         |         |         |                   |
 print_cov.dart                              |  100.00 |  100.00 |   88.37 |...,149,205,206,207|
 print_cov_constants.dart                    |    0.00 |    0.00 |    0.00 |    no unit testing|
lib/                                         |         |         |         |                   |
 test_cov_console.dart                       |    0.00 |    0.00 |    0.00 |    no unit testing|
---------------------------------------------|---------|---------|---------|-------------------|
 All files with unit testing                 |  100.00 |  100.00 |   88.37 |                   |
---------------------------------------------|---------|---------|---------|-------------------|

Optional parameter

If not given a FILE, "coverage/lcov.info" will be used.
-f, --file=<FILE>                      The target lcov.info file to be reported
-e, --exclude=<STRING1,STRING2,...>    A list of contains string for files without unit testing
                                       to be excluded from report
-l, --line                             It will print Lines & Uncovered Lines only
                                       Branch & Functions coverage percentage will not be printed
-i, --ignore                           It will not print any file without unit testing
-m, --multi                            Report from multiple lcov.info files
-c, --csv                              Output to CSV file
-o, --output=<CSV-FILE>                Full path of output CSV file
                                       If not given, "coverage/test_cov_console.csv" will be used
-t, --total                            Print only the total coverage
                                       Note: it will ignore all other option (if any), except -m
-p, --pass=<MINIMUM>                   Print only the whether total coverage is passed MINIMUM value or not
                                       If the value >= MINIMUM, it will print PASSED, otherwise FAILED
                                       Note: it will ignore all other option (if any), except -m
-h, --help                             Show this help

example run the tool with parameters

flutter pub run test_cov_console --file=coverage/lcov.info --exclude=_constants,_mock
---------------------------------------------|---------|---------|---------|-------------------|
File                                         |% Branch | % Funcs | % Lines | Uncovered Line #s |
---------------------------------------------|---------|---------|---------|-------------------|
lib/src/                                     |         |         |         |                   |
 print_cov.dart                              |  100.00 |  100.00 |   88.37 |...,149,205,206,207|
lib/                                         |         |         |         |                   |
 test_cov_console.dart                       |    0.00 |    0.00 |    0.00 |    no unit testing|
---------------------------------------------|---------|---------|---------|-------------------|
 All files with unit testing                 |  100.00 |  100.00 |   88.37 |                   |
---------------------------------------------|---------|---------|---------|-------------------|

report for multiple lcov.info files (-m, --multi)

It support to run for multiple lcov.info files with the followings directory structures:
1. No root module
<root>/<module_a>
<root>/<module_a>/coverage/lcov.info
<root>/<module_a>/lib/src
<root>/<module_b>
<root>/<module_b>/coverage/lcov.info
<root>/<module_b>/lib/src
...
2. With root module
<root>/coverage/lcov.info
<root>/lib/src
<root>/<module_a>
<root>/<module_a>/coverage/lcov.info
<root>/<module_a>/lib/src
<root>/<module_b>
<root>/<module_b>/coverage/lcov.info
<root>/<module_b>/lib/src
...
You must run test_cov_console on <root> dir, and the report would be grouped by module, here is
the sample output for directory structure 'with root module':
flutter pub run test_cov_console --file=coverage/lcov.info --exclude=_constants,_mock --multi
---------------------------------------------|---------|---------|---------|-------------------|
File                                         |% Branch | % Funcs | % Lines | Uncovered Line #s |
---------------------------------------------|---------|---------|---------|-------------------|
lib/src/                                     |         |         |         |                   |
 print_cov.dart                              |  100.00 |  100.00 |   88.37 |...,149,205,206,207|
lib/                                         |         |         |         |                   |
 test_cov_console.dart                       |    0.00 |    0.00 |    0.00 |    no unit testing|
---------------------------------------------|---------|---------|---------|-------------------|
 All files with unit testing                 |  100.00 |  100.00 |   88.37 |                   |
---------------------------------------------|---------|---------|---------|-------------------|
---------------------------------------------|---------|---------|---------|-------------------|
File - module_a -                            |% Branch | % Funcs | % Lines | Uncovered Line #s |
---------------------------------------------|---------|---------|---------|-------------------|
lib/src/                                     |         |         |         |                   |
 print_cov.dart                              |  100.00 |  100.00 |   88.37 |...,149,205,206,207|
lib/                                         |         |         |         |                   |
 test_cov_console.dart                       |    0.00 |    0.00 |    0.00 |    no unit testing|
---------------------------------------------|---------|---------|---------|-------------------|
 All files with unit testing                 |  100.00 |  100.00 |   88.37 |                   |
---------------------------------------------|---------|---------|---------|-------------------|
---------------------------------------------|---------|---------|---------|-------------------|
File - module_b -                            |% Branch | % Funcs | % Lines | Uncovered Line #s |
---------------------------------------------|---------|---------|---------|-------------------|
lib/src/                                     |         |         |         |                   |
 print_cov.dart                              |  100.00 |  100.00 |   88.37 |...,149,205,206,207|
lib/                                         |         |         |         |                   |
 test_cov_console.dart                       |    0.00 |    0.00 |    0.00 |    no unit testing|
---------------------------------------------|---------|---------|---------|-------------------|
 All files with unit testing                 |  100.00 |  100.00 |   88.37 |                   |
---------------------------------------------|---------|---------|---------|-------------------|

Output to CSV file (-c, --csv, -o, --output)

flutter pub run test_cov_console -c --output=coverage/test_coverage.csv

#### sample CSV output file:
File,% Branch,% Funcs,% Lines,Uncovered Line #s
lib/,,,,
test_cov_console.dart,0.00,0.00,0.00,no unit testing
lib/src/,,,,
parser.dart,100.00,100.00,97.22,"97"
parser_constants.dart,100.00,100.00,100.00,""
print_cov.dart,100.00,100.00,82.91,"29,49,51,52,171,174,177,180,183,184,185,186,187,188,279,324,325,387,388,389,390,391,392,393,394,395,398"
print_cov_constants.dart,0.00,0.00,0.00,no unit testing
All files with unit testing,100.00,100.00,86.07,""

Installing

Use this package as an executable

Install it

You can install the package from the command line:

dart pub global activate test_cov_console

Use it

The package has the following executables:

$ test_cov_console

Use this package as a library

Depend on it

Run this command:

With Dart:

 $ dart pub add test_cov_console

With Flutter:

 $ flutter pub add test_cov_console

This will add a line like this to your package's pubspec.yaml (and run an implicit dart pub get):

dependencies:
  test_cov_console: ^0.2.2

Alternatively, your editor might support dart pub get or flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:test_cov_console/test_cov_console.dart';

example/lib/main.dart

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
        // This makes the visual density adapt to the platform that you run
        // the app on. For desktop platforms, the controls will be smaller and
        // closer together (more dense) than on mobile platforms.
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(
          // Column is also a layout widget. It takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          //
          // Invoke "debug painting" (press "p" in the console, choose the
          // "Toggle Debug Paint" action from the Flutter Inspector in Android
          // Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
          // to see the wireframe for each widget.
          //
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

Author: DigitalKatalis
Source Code: https://github.com/DigitalKatalis/test_cov_console 
License: BSD-3-Clause license

#flutter #dart #test