How to add a custom library to a scratch file

Using require and relative paths.

Here is a crazy example of using lodash in a scratch file:

const _ = require('./../../../DEV/node_modules/lodash');

var anything = [1, 2];

_.map(anything, function (item) {
    console.log('Working >-P');
    return item;
});

var path = require('path');
_require = require;
require = function (p) {
  var absPath = path.join(process.cwd(), p);
  var relPath = path.relative(__dirname, absPath);
  return _require(relPath);
}

var Query = require('./server/libs/query_builder.js');

A bit late to answer, but if you replace the require function as I show above you can use it normally.


In fact, you can just add a package.json file to your scratches.

You could create one manually, but the following may be more practical:

Right click on any of your scratch files, then select "Open in terminal". You'll notice that it will open the terminal directly in the folder of the scratches. That's a folder such as C:\Users\ba\AppData\Roaming\JetBrains\WebStorm2020.2\scratches.

Since you are in the correct directory now, you can just run npm init from that terminal to create your package.json file. (You will be prompted with a bunch of questions, but you can just press enter for all questions if you are fine with the default values)

This file will just show up in your scratches along with your other files.


To answer your specific question, if you want to add lodash to those packages, you can open the terminal in the way mentioned above. This terminal will be in the correct folder. And then you can just run your npm install lodash from there.