How to add a custom library to a scratch file

4.5k views Asked by At

In PhpStorm/WebStorm how can I add a custom library so that the file compiles? In my case it would be Lodash?

I tried to add lodash to global libs but it did not help...

4

There are 4 answers

0
Amio.io On BEST ANSWER

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;
});
2
bvdb On

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.

0
matheus conceição On
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.

0
Przemek Nowak On

Well I would suggest in this case to use plugin named Quokka.js available for Webstorm and other JetBrains tools.

It's recognise automatically the libraries from node_modules and have a lot of other features (work much better that pure scratch files).

When you will install it the default scratch Javascript and Typescript files will work with Quokka.

You will find the details on the official tool page: https://quokkajs.com/

Please select JET BRAINS tool on main page. Hope it helps.