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.
- Download Node.js: Go to the official Node.js website and download the installer for your operating system.
- Install Node.js: Run the downloaded installer and follow the prompts to install Node.js and npm (Node Package Manager).
- Verify Installation: To ensure Node.js and npm are installed correctly, open your terminal or command prompt and run the following commands: 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.
- Download VSC: Visit the Visual Studio Code website to download the installer for your OS.
- Install VSC: Open the downloaded file and follow the installation instructions.
- 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.
- Open Extensions Panel: Click on the Extensions icon in the sidebar or use the shortcut (
Ctrl+Shift+Xon Windows/Linux,Cmd+Shift+Xon macOS). - Search for Prettier: In the Extensions panel, type
Prettierin the search bar. - Install Prettier: Find the Prettier - Code formatter extension by Esben Petersen and click the
Installbutton.
JavaScript (ES6) Code Snippets
This extension provides code snippets for JavaScript (ES6 syntax), making it easier to write JavaScript code.
- Search for JavaScript Snippets: In the Extensions panel, search for
JavaScript (ES6) code snippets. - Install the Extension: Find the extension by Charalampos Karypidis and click the
Installbutton.
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 (usuallyindex.js). You can press Enter to accept the default values. - After completing the steps, a
package.jsonfile 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.jsin 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) orCmd+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.jsonfile will be created in a.vscodefolder. This file tells Visual Studio Code how to run and debug your application. - Place a breakpoint in your
index.jsby clicking on the left side of the line number where you want the code to pause. For instance, click to the left ofconsole.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.jsonfile in your project. If not, create it by runningnpm initand following the setup prompts. - To add
uglify-jsas a development dependency, open your terminal, navigate to your project’s root directory, and run: This command installsuglify-jsand adds it to thedevDependenciessection of yourpackage.jsonfile.
Step 2: Add an npm Script for uglify-js
- Open your
package.jsonfile in a text editor. - Find the
"scripts"section. If it doesn’t exist, you can add it as follows: -
Add a new script for
This script tellsuglify-js. Modify the scripts section to include aminifyscript:uglify-jsto minifyindex.jsand output the result toindex.min.js. -
Save the changes to your
package.jsonfile.
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
- First, install
lodashby runningnpm install lodashin your project directory. - Create a file named
test1.js. -
In
test1.js, use the CommonJSrequiresyntax to includelodash. Then, use itscapitalizefunction to print “Hello world” with the first letter capitalized:
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
- To use ES6
importsyntax, ensure that yourpackage.jsonincludes"type": "module". This allows you to use ES6 modules natively in Node.js. - Create a file named
test2.js. -
In
test2.js, use the ES6importsyntax to includelodash. Then, use itscapitalizefunction similarly:
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 commandnode test1.jsin your terminal. - To run
test2.js, use the commandnode test2.js. Make sure your Node.js version supports ES6 modules and yourpackage.jsonis 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:
-
Open Your Project in Visual Studio Code: Make sure your project folder is open in VSC.
-
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) orCmd+Shift+D(macOS). -
Create or Open
launch.jsonFile: - If you haven’t created a
launch.jsonfile yet, click on the ‘create a launch.json file’ link, then select ‘Node.js’ to set up a default debug configuration. -
If you already have a
launch.jsonfile, open it by clicking on the gear icon in the Debug view. -
Modify the
launch.jsonFile: - Look for the configuration section (usually named “Launch Program” or similar).
- Replace the
programattribute with"${file}". This special variable tells Visual Studio Code to debug the currently active file in the editor. -
It should look something like this:
-
Save
launch.jsonFile: 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 eslintto install ESLint globally.
-
Local Installation:
- Navigate to your project directory in the terminal.
- Run
npm initif you haven’t already initialized your project with apackage.jsonfile. - 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@latestoreslint --initin your project directory. This will guide you through setting up a configuration file for your project and create aeslint.config.jsfile 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) orCmd+Shift+X(macOS). - Search for
ESLintin the extensions marketplace. - Find the ESLint extension by Dirk Baeumer and click the
Installbutton.
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 forESLint, 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
}
}
];