Skip to content

Commit

Permalink
fix: auto generated eslint config file, close unplugin#69 (unplugin#108)
Browse files Browse the repository at this point in the history
Co-authored-by: Anthony Fu <[email protected]>
  • Loading branch information
muzaisimao and antfu authored Jan 12, 2022
1 parent bcdedd8 commit a9a57b0
Show file tree
Hide file tree
Showing 6 changed files with 101 additions and 8 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -80,3 +80,4 @@ dist
# IDE
.idea
auto-imports.d.ts
.eslintrc-auto-import.json
31 changes: 31 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,14 @@ AutoImport({
}
],

// Generate corresponding .eslintrc-auto-import.json file.
// eslint globals Docs - https://eslint.org/docs/user-guide/configuring/language-options#specifying-globals
eslintrc: {
enabled: false, // Default `false`
filepath: './.eslintrc-auto-import.json', // Default `./.eslintrc-auto-import.json`
globalsPropValue: true // Default `true`, (true | false | 'readonly' | 'readable' | 'writable' | 'writeable')
},

// custom resolvers
// see https://github.com/antfu/unplugin-auto-import/pull/23/
resolvers: [
Expand All @@ -221,6 +229,29 @@ Refer to the [type definitions](./src/types.ts) for more options.

See [src/presets](./src/presets).

## ESLint - eslint(no-undef)

Configure `options.eslintrc`, and modify your eslint configuration file.

Example:

```ts
// .eslintrc.js

module.exports = {
/* ... */
extends: [
// ...
'./.eslintrc-auto-import.json',
],
}

```

ESLint Docs: [Extending Configuration Files](https://eslint.org/docs/user-guide/configuring/configuration-files#extending-configuration-files)

> Note: `.eslintrc-auto-import.json` is generated automatically, If the configuration file changes do not take effect in time, please check the configuration file, restart eslint server or the editor
## FAQ

### Compare to [`vue-global-api`](https://github.com/antfu/vue-global-api)
Expand Down
24 changes: 24 additions & 0 deletions src/core/eslintrc.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import type { ESLintGlobalsPropValue, ESLintrc, ImportsFlatMap } from '../types'

interface ESLintConfigs {
globals: Record<string, ESLintGlobalsPropValue>
}

// const __comment__ = 'Generated by `unplugin-auto-import`'

export function generateESLintConfigs(
imports: ImportsFlatMap,
resolvedImports: ImportsFlatMap = {},
eslintrc: ESLintrc,
) {
const eslintConfigs: ESLintConfigs = { globals: {} };

[
...Object.entries(imports),
...Object.entries(resolvedImports),
]
.sort((a, b) => a[0].localeCompare(b[0]))
.forEach(([name]) => { eslintConfigs.globals[name] = eslintrc.globalsPropValue || true })
const jsonBody = JSON.stringify(eslintConfigs, null, 2)
return jsonBody
}
8 changes: 7 additions & 1 deletion src/core/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { toArray } from '@antfu/utils'
import { createFilter } from '@rollup/pluginutils'
import { isPackageExists } from 'local-pkg'
import { presets } from '../presets'
import type { ImportsFlatMap, Options, ResolvedOptions, ResolvedResult } from '../types'
import type { ESLintrc, ImportsFlatMap, Options, ResolvedOptions, ResolvedResult } from '../types'

export function resolveOptions(options: Options = {}, root = process.cwd()): ResolvedOptions {
const imports = flattenImportsMap(options.imports, options.presetOverriding)
Expand All @@ -12,6 +12,11 @@ export function resolveOptions(options: Options = {}, root = process.cwd()): Res
dts = isPackageExists('typescript'),
} = options

const eslintrc: ESLintrc = options.eslintrc || {}
eslintrc.enabled = eslintrc.enabled === undefined ? false : eslintrc.enabled
eslintrc.filepath = eslintrc.filepath || './.eslintrc-auto-import.json'
eslintrc.globalsPropValue = eslintrc.globalsPropValue === undefined ? true : eslintrc.globalsPropValue

const resolved: ResolvedOptions = {
sourceMap: false,
resolvedImports: {},
Expand All @@ -29,6 +34,7 @@ export function resolveOptions(options: Options = {}, root = process.cwd()): Res
options.include || [/\.[jt]sx?$/, /\.vue$/, /\.vue\?vue/, /\.svelte$/],
options.exclude || [/[\\/]node_modules[\\/]/, /[\\/]\.git[\\/]/],
),
eslintrc,
}

return resolved
Expand Down
18 changes: 12 additions & 6 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,22 @@ import { throttle } from '@antfu/utils'
import type { Options } from './types'
import { resolveOptions } from './core/options'
import { transform } from './core/transform'
import { generateDeclaration as _generateDeclaration } from './core/dts'
import { generateDeclaration } from './core/dts'
import { generateESLintConfigs } from './core/eslintrc'

export default createUnplugin<Options>((options) => {
let resolved = resolveOptions(options)

if (!Object.keys(resolved.imports).length && !resolved.resolvers.length)
console.warn('[auto-import] plugin installed but no imports has defined, see https://github.com/antfu/unplugin-auto-import#configurations for configurations')

const generateDeclaration = throttle(500, false, () => {
if (!resolved.dts) return
fs.writeFile(resolved.dts, _generateDeclaration(resolved.imports, resolved.resolvedImports), 'utf-8')
const generateConfigFiles = throttle(500, false, () => {
if (resolved.dts)
fs.writeFile(resolved.dts, generateDeclaration(resolved.imports, resolved.resolvedImports), 'utf-8')

const { eslintrc } = resolved
if (eslintrc.enabled && eslintrc.filepath)
fs.writeFile(eslintrc.filepath, generateESLintConfigs(resolved.imports, resolved.resolvedImports, eslintrc), 'utf-8')
})

return {
Expand All @@ -26,13 +31,14 @@ export default createUnplugin<Options>((options) => {
async transform(code, id) {
const res = await transform(code, id, resolved)
if (res && resolved.resolvers.length)
generateDeclaration()
generateConfigFiles()

return res
},
vite: {
configResolved(config: any) {
resolved = resolveOptions(options, config.root)
generateDeclaration()
generateConfigFiles()
},
},
}
Expand Down
27 changes: 26 additions & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,25 @@ export type ImportsMap = Record<string, (string | ImportNameAlias)[]>
*/
export type ImportsFlatMap = Record<string, ResolvedResult>

export type ESLintGlobalsPropValue = boolean | 'readonly' | 'readable' | 'writable' | 'writeable'

export interface ESLintrc {
/**
* @default false
*/
enabled?: boolean
/**
* Filepath to save the generated eslint config
*
* @default './.eslintrc-auto-import.json'
*/
filepath?: string
/**
* @default true
*/
globalsPropValue?: ESLintGlobalsPropValue
}

export interface Options {
/**
* Preset names or custom imports map
Expand Down Expand Up @@ -92,6 +111,11 @@ export interface Options {
* @default false
*/
sourceMap?: boolean

/**
* Generate corresponding .eslintrc-auto-import.json file.
*/
eslintrc?: ESLintrc
}

export interface TransformOptions {
Expand Down Expand Up @@ -120,9 +144,10 @@ export interface TransformOptions {
resolvedImports?: ImportsFlatMap
}

export interface ResolvedOptions extends Omit<Required<Options>, 'imports' | 'resolvers' | 'dts' | 'include' | 'exclude'>, Required<TransformOptions> {
export interface ResolvedOptions extends Omit<Required<Options>, 'imports' | 'resolvers' | 'dts' | 'include' | 'exclude' | 'eslintrc'>, Required<TransformOptions> {
idFilter: (id: string) => boolean
dts: string | false
eslintrc: ESLintrc
}

export { PresetName }

0 comments on commit a9a57b0

Please sign in to comment.