-
Notifications
You must be signed in to change notification settings - Fork 4
/
convert-default-imports.js
59 lines (52 loc) · 1.75 KB
/
convert-default-imports.js
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
const fs = require('fs');
const path = require('path');
/**
* This transform converts stuff like:
*
* import moment from 'moment';
*
* to
*
* import * as moment from 'moment';
*
*/
module.exports = function(file, api) {
const directory = path.parse(file.path).dir;
const j = api.jscodeshift;
return j(file.source)
.find(j.ImportDefaultSpecifier)
.filter((node) => {
const libName = node.parentPath.parentPath.node.source.value;
if (libName.startsWith('.')) { // is a local file - bit of a rubbish check
const libPath = path.resolve(directory, libName);
try {
const fullLibPath = require.resolve(libPath);
const isJs = path.parse(fullLibPath).ext === '.js';
return !isJs; // convert all non js file imports (for webpack) `import template from './template.html';`
} catch (e) {
console.warn(`File "${libPath}" does not seem to exist. Assuming no default export`);
return true;
}
}
let mainFile;
try {
mainFile = require.resolve(libName);
} catch (e) {
console.warn(`Could not analyse "${libName}" for a default export, assuming it does not have one`);
return true;
}
const mainFileContents = fs.readFileSync(mainFile).toString();
try {
const hasDefault = j(mainFileContents).find(j.AssignmentExpression, {left: {object: {name: 'exports'}, property: {name: 'default'}}}).length > 0;
return !hasDefault;
} catch (e) {
console.warn(`Could not analyse "${libName}" for a default export, assuming it does not have one`);
return true;
}
})
.replaceWith(({node}) => {
node.type = 'ImportNamespaceSpecifier';
return node;
})
.toSource();
};