How to use underscore in Visual Studio Code without "activating" first?

Viewed 661

I tried to use underscore in Visual Studio Code and only if I use this line of code at the beginning:

var _ = require('underscore');

The output is correctly working. If I delete it, the output gives the following error:

ReferenceError: _ is not defined

Is it possible to "install the library of underscore permamently in visual studio code", so that I dont need every time the code from above? Or there are some libraries that you need to "activate" with a line of code first every time.

PS: The word library is a bit new for me, so maybe I am using it wrong.

4 Answers

it is possible to "install the library of underscore permamently in visual studio code"

Short answer, No.

You always have to import your dependencies, and this is a good thing. It helps when working on larger projects to know where all of your code is coming from. The less "magic" the better. Boring code is usually better code. If nothing else, its easier to debug and maintain.

This isn't possible. You must understand that each file should stand by itself, the file is not run by your vscode, so there's no reason for it to be dependent on vscode and it's installed packages/libraries.

think that your code is running in a completely different and isolated environment

so if you want to use other code (such as packages/libraries that you can install) you must explicitly import them and include their files in your project (most likely under node_modules).

Let's look at that line of code:

var _ = require("underscore");

Basically, you're defining the variable _ to the value of the underscore library. require() is a function built in to Node.js, which returns that module/library.

You can't skip this line because without it, there is no variable called _. This has nothing to do with VSCode, just the language itself.

A package manager such as NPM must be installed in order to use require to import the library you want, underscore in this case.

You can download NPM by having NodeJs in your OS.

If you haven't installed it yet, just type in terminal: npm install underscore

Code example

const _ = require("underscore");

const suspectNames = ["Miss Scarlet", "Colonel Mustard", "Mr. White"];


_.each(suspectNames, (suspectName) => console.log(suspectName));

Related