Hi I'm trying to write a codemod which moves my require statement from top of the file to inside class constructor function.
const moduleA = require('moduleA');
const moduleB = require('../moduleB');
class Example {
constructor(context) {
this.lazy(
"moduleA",
() => new moduleA(context)
);
this.lazy(
"moduleB",
() => new moduleB(context)
);
}
lazy() {
}
async callThis() {
this.moduleA.callThatMethod();
}
}
module.exports = Example;
These require statements on top of the file taking long time, which is only used if that API is called at-least once. So as the require is being cached by Node.js at process level anyway. I'm trying to move the require
statement inside the arrow function.
Like Below
class Example {
constructor(context) {
super(context);
this.lazy("moduleA", () => {
const moduleA = require('moduleA');
return new moduleA()
}
this.lazy("moduleB", () => {
const moduleB = require('../moduleB');
return new moduleB()
}
}
async callThis() {
this.moduleA.callThatMethod();
}
}
I'm having trouble achieving this, because i dunno how to select the "lazy" function defined and then move the top require.
Any help is much appreciated Thanks
You don't need jscodeshift for such a simple transformation. With my tool Putout you can easily remove top-level
require
, and add it tolazy
function:Try it
If you need to filter out
this.lazy
and have a lot of different modules, you can use PutoutScript with template values__a
and__b
used to determine and replaceIdentifier
fromVariableDeclarator
id
andStringLiteral
fromCallExpression
callee
insideVariableDeclarator
init
inconst moduleA = require('moduleA')
VariableDeclaration
:Try it