1 | const fs = require('fs')
|
2 | const nodePath = require('path')
|
3 | const resolve = require('resolve')
|
4 |
|
5 | const readJSON = (filePath, state) => {
|
6 | const srcPath = nodePath.resolve(state.file.opts.filename)
|
7 | const jsonPath = nodePath.join(srcPath, '..', filePath)
|
8 |
|
9 | if (fs.existsSync(jsonPath + '.json')) {
|
10 | console.log('json', require(jsonPath))
|
11 | return require(jsonPath)
|
12 | }
|
13 |
|
14 | const file = resolve.sync(filePath, {
|
15 | basedir: nodePath.dirname(srcPath)
|
16 | })
|
17 |
|
18 | if (fs.existsSync(file)) {
|
19 | const fileText = fs.readFileSync(file, 'utf8')
|
20 |
|
21 | try {
|
22 | return JSON.parse(fileText)
|
23 | } catch (e) {
|
24 |
|
25 | return null
|
26 | }
|
27 | }
|
28 | }
|
29 |
|
30 | const replacePath = (path, node) => {
|
31 | path.replaceWithMultiple([].concat(node))
|
32 | }
|
33 |
|
34 | module.exports = function({ types: t }) {
|
35 | function isMatchedRequireCall(node, state) {
|
36 | const re = new RegExp(state.opts.matchPattern, 'g')
|
37 |
|
38 | return (
|
39 | t.isIdentifier(node.callee, { name: 'require' }) &&
|
40 | t.isLiteral(node.arguments[0]) &&
|
41 | !t.isTemplateLiteral(node.arguments[0]) &&
|
42 | node.arguments[0].value.match(re)
|
43 | )
|
44 | }
|
45 |
|
46 | function createConstVarDeclaration(identifier, value) {
|
47 | return t.VariableDeclaration('const', [
|
48 | t.VariableDeclarator(t.Identifier(identifier), t.valueToNode(value))
|
49 | ])
|
50 | }
|
51 |
|
52 | function createExpression(value) {
|
53 | return t.expressionStatement(t.valueToNode(value))
|
54 | }
|
55 |
|
56 | return {
|
57 | visitor: {
|
58 | CallExpression(path, state) {
|
59 | const { node } = path
|
60 |
|
61 | if (isMatchedRequireCall(node, state)) {
|
62 | const json = readJSON(node.arguments[0].value, state)
|
63 |
|
64 | if (json) {
|
65 | replacePath(path, createExpression(json))
|
66 | }
|
67 | }
|
68 | },
|
69 |
|
70 | ImportDeclaration: (path, state) => {
|
71 | const { node } = path
|
72 |
|
73 | if (!node.source.value.match(/.json$/)) return
|
74 |
|
75 | const json = readJSON(node.source.value, state)
|
76 |
|
77 | if (json) {
|
78 | const nodeArr = node.specifiers.map(n => {
|
79 | const field = n.local.name
|
80 |
|
81 | switch (true) {
|
82 | case t.isImportDefaultSpecifier(n):
|
83 | case t.isImportNamespaceSpecifier(n):
|
84 | return createConstVarDeclaration(field, json)
|
85 | case t.isImportSpecifier(n):
|
86 | return createConstVarDeclaration(
|
87 | field,
|
88 | json[n.imported ? n.imported.name : field]
|
89 | )
|
90 | }
|
91 | })
|
92 |
|
93 | replacePath(path, nodeArr)
|
94 | }
|
95 | },
|
96 |
|
97 | MemberExpression(path, state) {
|
98 | const { node } = path
|
99 |
|
100 | if (isMatchedRequireCall(node.object, state)) {
|
101 | const json = readJSON(node.object.arguments[0].value, state)
|
102 |
|
103 | if (json) {
|
104 | replacePath(path, createExpression(json[node.property.name]))
|
105 | }
|
106 | }
|
107 | }
|
108 | }
|
109 | }
|
110 | }
|