-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathuse-alias.js
184 lines (165 loc) · 5.93 KB
/
use-alias.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
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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
const babel = require('@babel/core')
const path = require('path')
const fs = require('fs')
const checkIgnoreDepth = require('../helpers/check-ignore-depth')
const findProjectRoot = require('../helpers/find-project-root')
const getProperties = require('../helpers/get-properties')
const createFixer = require('../helpers/create-fixer')
const isAliasPath = require('../helpers/is-alias-path')
const values = Object.values || ((obj) => Object.keys(obj).map((e) => obj[e]))
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'],
},
},
chainedExtensions: {
type: 'array',
uniqueItems: true,
items: {
type: 'string',
},
},
alias: {
type: 'object',
},
},
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, or use the
// provided alias map.
let alias = options.alias
if (!alias) {
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 })
},
}
}
}
// Build array of alias paths.
const cwd = projectRootAbsolutePath || process.cwd()
const aliasPaths = values(alias).map((a) => path.join(cwd, a))
const hasError = (val) => {
if (!val) return false // template literals will have undefined val
const { ignoreDepth, projectRoot, extensions, allowDepthMoreOrLessThanEquality } = options
let {chainedExtensions = []} = options;
// Be forgiving if the config provides "ext" or ".ext"
chainedExtensions = chainedExtensions.map(
ext => ext.startsWith('.') ? ext : `.${ext}`
);
// 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 {
suggestFix: false,
message: 'Invalid project root specified',
}
}
const resolvedPath = path.resolve(filePath, val)
const pathExt = path.extname(val);
// If no extension is present, or if the extension is explicitly
// allowlisted as chainable, resolve the extension to a `.js` file.
const resolvedExt = !pathExt || chainedExtensions.includes(pathExt)
? '.js'
: ''
let pathExists = checkPath(resolvedPath, resolvedExt)
if (extensions && !pathExists) {
pathExists = extensions.filter((ext) => checkPath(resolvedPath, ext)).length
}
const isAliased = aliasPaths.some((aliasPath) =>
isAliasPath(resolvedPath, aliasPath)
)
const error = isAliased && pathExists && val.match(/\.\.\//) // matches, exists, and starts with ../,
return error && { suggestFix: true, message: 'Do not use relative path for aliased modules' }
}
const reportError = ({ node, source, error }) => {
context.report({
node,
message: error.message,
loc: source.loc,
fix: error.suggestFix && createFixer({ alias, filePath, cwd, node }),
})
}
return {
ImportDeclaration(node) {
const error = hasError(node.source.value)
if (error) {
reportError({ node, source: node.source, error })
}
},
CallExpression(node) {
const val = node.callee.name || node.callee.type
if (val === 'Import' || val === 'require') {
const error = hasError(node.arguments[0].value)
error && reportError({ node, source: node.arguments[0], error })
}
},
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
const error = hasError(node.source.value)
if (error) {
reportError({ node, source: node.source, error })
}
},
}
},
}