-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathuse-alias.js
More file actions
165 lines (148 loc) · 5.61 KB
/
use-alias.js
File metadata and controls
165 lines (148 loc) · 5.61 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
const babel = require('@babel/core')
const path = require('path')
const fs = require('fs')
const { resolvePath } = require('babel-plugin-module-resolver')
const checkIgnoreDepth = require('../helpers/check-ignore-depth')
const findProjectRoot = require('../helpers/find-project-root')
const getProperties = require('../helpers/get-properties')
const checkPath = (path, ext) => fs.existsSync(`${path}${ext}`) || fs.existsSync(`${path}/index${ext}`)
module.exports = {
meta: {
docs: {
description: 'Warn when using relative paths to modules aliased',
category: 'Fill me in',
recommended: false,
},
fixable: 'code',
schema: [
{
type: 'object',
properties: {
ignoreDepth: {
type: 'integer',
minimum: 0,
},
allowDepthMoreOrLessThanEquality: {
type: 'boolean',
},
projectRoot: {
type: 'string',
},
extensions: {
type: 'array',
uniqueItems: true,
items: {
type: 'string',
enum: ['.ts', '.tsx', '.jsx'],
},
},
},
additionalProperties: false,
},
],
},
create: function (context) {
const filename = context.getFilename()
const filePath = path.dirname(filename)
// Plugin options.
const options = getProperties(context.options)
const projectRootAbsolutePath = findProjectRoot(filePath, options.projectRoot)
// Find alias via babel-plugin-module-resolver config.
let alias = {}
// Look for default babel.config file
let configOptions = babel.loadPartialConfig().options
// No plugins found, look for .babelrc config file
if (configOptions.plugins.length === 0) {
configOptions = babel.loadPartialConfig({
configFile: './.babelrc',
}).options
}
try {
const validPluginNames = new Set(['babel-plugin-module-resolver', 'module-resolver'])
const [moduleResolver] = configOptions.plugins.filter((plugin) => {
if (validPluginNames.has(plugin.file && plugin.file.request)) {
return plugin
}
})
alias = moduleResolver.options.alias
} catch (error) {
const message = 'Unable to find config for babel-plugin-module-resolver'
return {
ImportDeclaration(node) {
context.report({ node, message, loc: node.source.loc })
},
CallExpression(node) {
context.report({ node, message, loc: node.arguments[0].loc })
},
}
}
// Resolve alias paths.
const cwd = projectRootAbsolutePath || process.cwd()
const resolvedAlias = Object.fromEntries(
Object.entries(alias).map(([aliasName, aliasPath]) => [aliasName, path.join(cwd, aliasPath)]),
)
const run = ({ node, source }) => {
const val = source.value
if (!val) return false // template literals will have undefined val
const { ignoreDepth, projectRoot, extensions, allowDepthMoreOrLessThanEquality } = options
// Ignore if directory depth matches options.
if (checkIgnoreDepth({ ignoreDepth, path: val, allowDepthMoreOrLessThanEquality })) return false
// Error if projectRoot option specified but cannot be resolved.
if (projectRoot && !projectRootAbsolutePath) {
return context.report({
node,
message: 'Invalid project root specified',
loc: source.loc,
})
}
const containedAlias = Object.keys(resolvedAlias).find((name) => val.startsWith(name)) //new Regex(`^${alias}(\\/|$)`).test(val))
const resolvedPath = containedAlias
? val.replace(containedAlias, resolvedAlias[containedAlias])
: path.resolve(filePath, val)
const [insideAlias] =
Object.entries(resolvedAlias).find(([aliasName, aliasPath]) => resolvedPath.startsWith(aliasPath)) || []
const resolvedExt = path.extname(val) ? '' : '.js'
const isSubpath = resolvedPath.startsWith(filePath)
let pathExists = checkPath(resolvedPath, resolvedExt)
if (extensions && !pathExists) {
pathExists = extensions.filter((ext) => checkPath(resolvedPath, ext)).length
}
if (insideAlias && pathExists && val.match(/\.\.\//)) {
// matches, exists, and starts with ../,
const newPath = resolvedPath.replace(resolvedAlias[insideAlias], '')
const replacement = path.join(insideAlias, newPath).replace(/\\/g, '/')
context.report({
node,
message: 'Do not use relative path for aliased modules',
loc: source.loc,
fix: (fixer) => fixer.replaceTextRange([source.range[0] + 1, source.range[1] - 1], replacement),
})
} else if (containedAlias && isSubpath) {
const replacement = resolvePath(val, filename, { alias })
context.report({
node,
message: 'Do not use aliased path for subpath import',
loc: source.loc,
fix: (fixer) => fixer.replaceTextRange([source.range[0] + 1, source.range[1] - 1], replacement),
})
}
}
return {
ImportDeclaration(node) {
run({ node, source: node.source })
},
CallExpression(node) {
const val = node.callee.name || node.callee.type
if (val === 'Import' || val === 'require') {
run({ node, source: node.arguments[0] })
}
},
ImportExpression(node) {
// dynamic import was erroneously using visitorKey for
// call expressions https://github.com/babel/babel/pull/10828
// adding ImportExpression for new versions of @babel/eslint-parser
run({ node, source: node.source })
},
}
},
}