This repository was archived by the owner on Jun 16, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathvariable-require-to-import-default.js
More file actions
73 lines (64 loc) · 2.08 KB
/
variable-require-to-import-default.js
File metadata and controls
73 lines (64 loc) · 2.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/**
* Transform
*
* const Lib = require('lib');
*
* to
*
* import Lib from 'lib';
*
* Only on global context
*/
// on https://astexplorer.net: Press ctrl+space for code completion
import Logger from './utils/logger'
import {isTopNode} from './utils/filters'
function transformer(file, api, options) {
const j = api.jscodeshift
const logger = new Logger(file, options)
// ------------------------------------------------------------------ SEARCH
const nodes = j(file.source)
.find(j.VariableDeclaration, {
declarations: [{
init: {
type: 'CallExpression',
callee: {
name: 'require'
}
}
}]
}).filter(isTopNode)
logger.log(`${nodes.length} nodes will be transformed`)
// ----------------------------------------------------------------- REPLACE
return nodes.replaceWith(path => {
const rest = []
const imports = []
for (const declaration of path.node.declarations) {
if (j.CallExpression.check(declaration.init)
&& declaration.init.callee.name === 'require'){
const importSpecifier = j.importDefaultSpecifier(declaration.id)
const sourcePath = declaration.init.arguments.shift()
if (declaration.init.arguments.length) {
logger.error(`${logger.lines(declaration)} too many arguments.`
+ 'Aborting transformation')
return file.source
}
if (!j.Literal.check(sourcePath)) {
logger.error(`${logger.lines(declaration)} bad argument.`
+ 'Expecting a string literal, got '
+ j(sourcePath).toSource()
+ '`. Aborting transformation')
return file.source
}
imports.push(j.importDeclaration([importSpecifier], sourcePath))
} else {
rest.push(declaration)
}
}
if (rest.length > 0) {
logger.warn(`${logger.lines(path.node)} introduced leftover`)
return [...imports, j.variableDeclaration(path.node.kind, rest)]
}
return imports
}).toSource()
}
export default transformer