Conversation
|
Test failure on the destructuring commit |
|
@epixa do you think it's worth doing this in multiple prs? |
|
I definitely do, yeah. The changes are fundamentally not complex, but there are so many of them... |
|
Cool |
|
There's a different test failure this time. You can rebase this as well to knock out the first commit. |
3e60b49 to
ba19f89
Compare
|
I played around with jscodeshift some time ago and tried this on Kibana: module.exports = function(fileInfo, api) {
var j = api.jscodeshift;
var root = j(fileInfo.source);
root
.find(j.VariableDeclaration, {
declarations: [{
type: 'VariableDeclarator',
init: {
type: 'CallExpression',
callee: {
type: 'Identifier',
name: 'require',
},
},
}],
})
.filter(isTopLevel)
.forEach(function(path) {
const dec = path.value.declarations[0];
const id = dec.id;
const source = dec.init.arguments[0];
const comments = path.value.comments;
const loc = path.value.loc;
path.replace(
j.importDeclaration(
[{
type: 'ImportDefaultSpecifier',
id
}],
source
)
);
path.value.loc = loc;
path.value.comments = comments;
});
root
.find(j.VariableDeclaration, {
declarations: [{
type: 'VariableDeclarator',
init: {
type: 'MemberExpression',
object: {
type: 'CallExpression',
callee: {
type: 'Identifier',
name: 'require'
},
},
},
}],
})
.filter(isTopLevel)
.forEach(function(path) {
const dec = path.value.declarations[0];
const name = dec.id;
const source = dec.init.object.arguments[0];
// We cannot transform require's which include function calls
if (source.type === 'CallExpression') return;
const id = dec.init.property;
const comments = path.value.comments;
const loc = path.value.loc;
let spec = {
type: 'ImportSpecifier',
id,
}
if (name.name !== id.name) {
spec['name'] = name;
}
path.replace(j.importDeclaration([spec], source));
path.value.loc = loc;
path.value.comments = comments;
});
return root.toSource();
};
function isTopLevel(path) {
return !path.parentPath.parentPath.parentPath.parentPath;
}and Seemed to work ok. Fun to play around with. Totally forgot about it, therefore no PR 🙈 (Thought I'd just mention jscodeshift as a fun tool when transforming code) Btw, http://astexplorer.net/ helps a lot when playing around with this. |
|
interesting, I played around with babel before going down the route I have now but the output messed with formatting too much. this seems to handle the require -> import really nicely. I wonder if I could use it to convert files where the require is passed directly to |
|
I struggled a bit with it, so it probably takes some fighting to get there ;) Might be some inspiration to get in https://github.com/5to6/5to6-codemod and https://github.com/rackt/rackt-codemod |
ba19f89 to
c65e136
Compare
c65e136 to
f37e0f4
Compare
|
LGTM |
This change is slightly more complex than #6072, it converts all require statements that referenced a sub-property of a module.