Skip to content

Setup VSC/Node.js

Use this guide to setup your development environment for JavaScript development.

Install Node.js

Before you start with JavaScript development, you need to have Node.js installed on your computer. Node.js is a runtime environment that allows you to run JavaScript outside a web browser.

  1. Download Node.js: Go to the official Node.js website and download the installer for your operating system.
  2. Install Node.js: Run the downloaded installer and follow the prompts to install Node.js and npm (Node Package Manager).
  3. Verify Installation: To ensure Node.js and npm are installed correctly, open your terminal or command prompt and run the following commands:
    node -v
    npm -v
    
    This will display the version of Node.js and npm installed on your system.

Install Visual Studio Code (VSC)

Visual Studio Code is a popular code editor among JavaScript developers. It’s lightweight, fast, and has a rich ecosystem of extensions.

  1. Download VSC: Visit the Visual Studio Code website to download the installer for your OS.
  2. Install VSC: Open the downloaded file and follow the installation instructions.
  3. Launch VSC: After installation, launch Visual Studio Code.

Add Extensions

Extensions in VSC can greatly enhance your development experience. Here are two essential extensions for JavaScript development:

Prettier - Code Formatter

Prettier is an opinionated code formatter that supports many languages, including JavaScript.

  1. Open Extensions Panel: Click on the Extensions icon in the sidebar or use the shortcut (Ctrl+Shift+X on Windows/Linux, Cmd+Shift+X on macOS).
  2. Search for Prettier: In the Extensions panel, type Prettier in the search bar.
  3. Install Prettier: Find the Prettier - Code formatter extension by Esben Petersen and click the Install button.

JavaScript (ES6) Code Snippets

This extension provides code snippets for JavaScript (ES6 syntax), making it easier to write JavaScript code.

  1. Search for JavaScript Snippets: In the Extensions panel, search for JavaScript (ES6) code snippets.
  2. Install the Extension: Find the extension by Charalampos Karypidis and click the Install button.

Using these extensions will improve your coding efficiency in JavaScript by providing quick access to common patterns and ensuring consistent formatting.

Create a package.json File and a Simple index.js

To start any JavaScript project, you need to create a package.json file. This file contains metadata about your project and manages the project’s dependencies, scripts, and more. Alongside, we’ll create a simple index.js file to print “Hello World” using a variable, which will also allow us to test the debugger in Visual Studio Code.

Step 1: Create package.json

  • Navigate to your project’s root directory in the terminal (or use the View->Terminal menu in VSC).
  • Run npm init. This command will prompt you to enter several pieces of information, like the project’s name, version, and entry point (usually index.js). You can press Enter to accept the default values.
  • After completing the steps, a package.json file will be created in your project directory.

Step 2: Create index.js

  • In the root of your project, create a file named index.js.
  • Open index.js in Visual Studio Code or your preferred text editor.
  • Add the following JavaScript code to index.js:
// Define a variable to hold the message
const message = "Hello World";

// Print the message to the console
console.log(message);

This code defines a variable message and prints its content to the console. It’s a simple example to test the functionality and the debugger.

In the latest version of VSC, you should now be able to run the code by pressing F5 (or Ctrl+F5 for no debugging). If you are using an older version, you may need to set up a launch.json file to run the code.

Step 3: Set Up Debugging in Visual Studio Code

  • Open your project in Visual Studio Code.
  • Go to the Debug panel by clicking on the Run and Debug icon on the sidebar, or press Ctrl+Shift+D (Windows/Linux) or Cmd+Shift+D (macOS).
  • Click on the “create a launch.json file” link, then select “Node.js” to set up debugging for your Node.js application.
  • A launch.json file will be created in a .vscode folder. This file tells Visual Studio Code how to run and debug your application.
  • Place a breakpoint in your index.js by clicking on the left side of the line number where you want the code to pause. For instance, click to the left of console.log(message);.
  • Start the debugger by clicking the green play button or pressing F5. The debugger will run your code and pause at the breakpoint, allowing you to inspect variables, step through code, and debug effectively.

With these steps, you have set up a basic JavaScript project with a package.json file, an index.js file for code, and the capability to debug your application using Visual Studio Code.

Install uglify-js for Minification

Step 1: Add uglify-js as a devDependency

  • Ensure you have a package.json file in your project. If not, create it by running npm init and following the setup prompts.
  • To add uglify-js as a development dependency, open your terminal, navigate to your project’s root directory, and run:
    npm install uglify-js --save-dev
    
    This command installs uglify-js and adds it to the devDependencies section of your package.json file.

Step 2: Add an npm Script for uglify-js

  • Open your package.json file in a text editor.
  • Find the "scripts" section. If it doesn’t exist, you can add it as follows:
    "scripts": {
      "start": "node index.js"
    }
    
  • Add a new script for uglify-js. Modify the scripts section to include a minify script:

    "scripts": {
      "start": "node index.js",
      "minify": "uglifyjs index.js -o index.min.js"
    }
    
    This script tells uglify-js to minify index.js and output the result to index.min.js.

  • Save the changes to your package.json file.

Now, whenever you want to minify your index.js file, you can run npm run minify in the terminal. This will create a minified version of your JavaScript file, named index.min.js, in your project directory. This script can be a part of your build process when preparing your application for production.

Install lodash for JavaScript Modules

Using lodash with require in test1.js

  1. First, install lodash by running npm install lodash in your project directory.
  2. Create a file named test1.js.
  3. In test1.js, use the CommonJS require syntax to include lodash. Then, use its capitalize function to print “Hello world” with the first letter capitalized:

    // test1.js
    const _ = require('lodash');
    
    const message = "hello world (lodash - require)";
    console.log(_.capitalize(message));
    

Here, require is the standard way to include modules in Node.js that is available in versions prior to ES6.

Using lodash with ES6 import in test2.js

  1. To use ES6 import syntax, ensure that your package.json includes "type": "module". This allows you to use ES6 modules natively in Node.js.
  2. Create a file named test2.js.
  3. In test2.js, use the ES6 import syntax to include lodash. Then, use its capitalize function similarly:

    // test2.js
    import _ from 'lodash';
    
    const message = "hello world (lodash - es6)";
    console.log(_.capitalize(message));
    

The ES6 import syntax is a more modern way to include modules and is part of the ES6 specification. It’s used commonly in front-end JavaScript frameworks and can be used in Node.js with the appropriate configuration.

Running the Files

  • To run test1.js, simply use the command node test1.js in your terminal.
  • To run test2.js, use the command node test2.js. Make sure your Node.js version supports ES6 modules and your package.json is correctly configured as mentioned earlier.

Both files will output “Hello world” to the console, but each uses a different syntax for including the lodash library.

Setting Up F5 for Debugging the Active File in Visual Studio Code

To configure Visual Studio Code to debug the active JavaScript file when you press F5, you’ll need to modify the launch.json file in your project. This setup allows you to quickly start debugging without manually selecting the file each time.

Here’s how you can set it up:

  1. Open Your Project in Visual Studio Code: Make sure your project folder is open in VSC.

  2. Access Debug View: Click on the Debug icon in the Activity Bar on the side of the window, or use the shortcut Ctrl+Shift+D (Windows/Linux) or Cmd+Shift+D (macOS).

  3. Create or Open launch.json File:

  4. If you haven’t created a launch.json file yet, click on the ‘create a launch.json file’ link, then select ‘Node.js’ to set up a default debug configuration.
  5. If you already have a launch.json file, open it by clicking on the gear icon in the Debug view.

  6. Modify the launch.json File:

  7. Look for the configuration section (usually named “Launch Program” or similar).
  8. Replace the program attribute with "${file}". This special variable tells Visual Studio Code to debug the currently active file in the editor.
  9. It should look something like this:

    {
        "type": "node",
        "request": "launch",
        "name": "Debug Current File",
        "program": "${file}"
    }
    
  10. Save launch.json File: After making the changes, save the file.

Now, whenever you press F5, Visual Studio Code will start debugging the currently active JavaScript file in the editor. This setup is particularly useful when working on projects with multiple JavaScript files and you need a quick way to debug the file you’re currently editing.

Assignment(s)

  • Make sure you can get a Node application up and running
    • Make sure you understand how VSC works (including extensions)
    • Make sure you understand how NodeJS works
    • Make sure you understand NPM and how to use it
    • Make sure you understand how to use the debugger in VSC
    • Make sure you understand how to use the terminal in VSC
    • Make sure you understand basic use of libraries

Install ESLint in Visual Studio Code

ESLint is a powerful tool that helps you to identify and fix problems in your JavaScript code. It’s widely used in the JavaScript community for enforcing code style and quality.

Step 1: Install ESLint Globally or Locally

You can install ESLint either globally or in your project’s local directory. It’s recommended to install it locally for each project to manage different configurations for different projects.

  • Global Installation (optional):

    • Open your terminal or command prompt.
    • Run npm install -g eslint to install ESLint globally.
  • Local Installation:

    • Navigate to your project directory in the terminal.
    • Run npm init if you haven’t already initialized your project with a package.json file.
    • Then, install ESLint locally by running npm install eslint --save-dev.

Step 2: Initialize ESLint Configuration

  • After installing, set up a configuration file by running npm init @eslint/config@latest or eslint --init in your project directory. This will guide you through setting up a configuration file for your project and create a eslint.config.js file in your project root containing the configuration settings.

Step 3: Install ESLint Extension in VSC

  • Open Visual Studio Code.
  • Go to the Extensions view by clicking the square icon on the sidebar, or by pressing Ctrl+Shift+X (Windows/Linux) or Cmd+Shift+X (macOS).
  • Search for ESLint in the extensions marketplace.
  • Find the ESLint extension by Dirk Baeumer and click the Install button.

Step 4: Configure ESLint in Visual Studio Code

  • After installation, you can configure ESLint by editing your project’s config file or the ESLint settings in the VSC settings JSON file.
  • To open the settings JSON file, go to File > Preferences > Settings, search for ESLint, and edit as needed.
  • You can customize rules, add plugins, and more, based on your project requirements.

With ESLint installed and configured in Visual Studio Code, your editor will automatically highlight issues and enforce the coding standards as specified in your ESLint configuration. This helps maintain a consistent code style and catch common coding errors.

You could try this code in a new file to see ESLint in action:

const a = "Hello World";

/* eslint quotes: ["error", "double"] */
const b = 'Hello World';

for (var i = 0; i < 10; i--) {
    console.log(i);
}

/* eslint eqeqeq: "error", curly: "warn" */
let c = 1;
if(c==1) 
    console.log("c is 1");

/*eslint camelcase: "error"*/
var my_favorite_color = "#112C85";
console.log(myfavoritecolor);

/* eslint id-match: ["error", "^[a-z][a-zA-Z0-9]*$", { "onlyDeclarations": true }] */
let MyVariable = 42; // Fejl, starter med stort bogstav
console.log(MyVariable);

// see https://eslint.org/docs/latest/rules/

If you have ESLint enabled, you may see warnings or errors in your code editor based on the ESLint rules you’ve set up. This is a great way to catch issues early and maintain code quality throughout your project.

Here is an example of a .eslintrc.js (eslint.config.mjs) file with some rules:

import globals from "globals";
import pluginJs from "@eslint/js";


/** @type {import('eslint').Linter.Config[]} */
export default [
  {languageOptions: { globals: globals.browser }},
  pluginJs.configs.recommended,
  {
    rules: {
      "eqeqeq": "error",
      "quotes": ["warn", "double"],
      "id-match": ["warn", "^[a-z][a-zA-Z0-9]*$", { "onlyDeclarations": true }],
      "curly": "warn",
      "no-unused-vars": "warn", // Warns about variables that are declared but not used
      "semi": ["warn", "always"], // Enforces the use of semicolons
      "no-console": "off", // Allows the use of console statements
      "indent": ["warn", 2] // Enforces consistent indentation of 2 spaces
    }
  }
];