gapmiss/obsidian-plugin-skill / .agents/skills/obsidian
obsidian
VerifiedComprehensive guidelines for Obsidian.md plugin development including ESLint rules from eslint-plugin-obsidianmd v0.6.0, TypeScript best practices, memory management, API usage (requestUrl vs fetch), UI/UX standards, popout window compatibility, community.obsidian.md submission process, and Scorecard optimization. Use when working with Obsidian plugins, main.ts files, manifest.json, Plugin class, MarkdownView, TFile, vault operations, or any Obsidian API development.
| File | Kind | Size |
|---|---|---|
| SKILL.md | skill md | 22.0 KB |
| reference/accessibility.md | markdown | 8.0 KB |
| reference/code-quality.md | markdown | 21.9 KB |
| reference/community-scanner.md | markdown | 10.8 KB |
| reference/css-styling.md | markdown | 10.7 KB |
| reference/eslint-setup.md | markdown | 72.3 KB |
| reference/file-operations.md | markdown | 6.1 KB |
| reference/memory-management.md | markdown | 6.3 KB |
| reference/submission.md | markdown | 5.2 KB |
| reference/type-safety.md | markdown | 1.5 KB |
| reference/ui-ux.md | markdown | 29.0 KB |
reference/eslint-setup.md
View on GitHub# Setting Up ESLint for Obsidian Community Plugin Submission
The Obsidian community plugin review runs an automated scan that checks your code against a specific set of lint rules. If your local ESLint setup doesn't match what the scanner checks, you'll submit with a clean local lint and get back a wall of violations.
This guide covers the complete setup so your local `npx eslint .` catches exactly what the community scanner catches.
## What the Community Scanner Actually Checks
The scanner runs `eslint-plugin-obsidianmd`'s recommended config, which bundles the `typescript-eslint` recommended type-checked rules itself (plus `import`, `@microsoft/sdl`, `depend`, `no-unsanitized`, and `eslint-comments`). `...obsidianmd.configs.recommended` alone gives you the same ruleset the scanner uses.
Full scanner behavior (rule sets, checks beyond ESLint, Scorecard mechanics) is documented in [community-scanner.md](community-scanner.md).
## Prerequisites
### For New Projects
```bash
npm install -D eslint typescript typescript-eslint obsidian eslint-plugin-obsidianmd
```
- **`obsidian` must be installed in your project.** v0.5.0 reads Obsidian's own type definitions and no longer installs `obsidian` for you. Without it, `no-unsupported-api` silently reports nothing. Sample-plugin projects already have it.
- `@eslint/js` and `@eslint/json` are **not** needed unless your own config imports them. If it does, `@eslint/json` must be 2.x (see [Upgrading from v0.4.x](#upgrading-from-v04x)).
- You don't need `@typescript-eslint/parser` separately — `typescript-eslint` provides the parser.
### Migrating Existing Projects (IMPORTANT)
If your project has old ESLint packages (common in plugins created before 2024), you must clean up before installing.
#### Quick Migration (One Command)
If you have TypeScript 4.x, this single command upgrades everything at once:
```bash
npm uninstall @typescript-eslint/eslint-plugin @typescript-eslint/parser eslint && \
npm install -D typescript@5 eslint@9 typescript-eslint obsidian eslint-plugin-obsidianmd
```
Then remove old config files:
```bash
rm -f .eslintrc .eslintrc.js .eslintrc.json .eslintrc.yml .eslintrc.yaml
```
#### Step-by-Step Migration
If the quick command fails or you prefer more control:
**1. Check your current setup:**
```bash
grep -E "@typescript-eslint|eslint|typescript" package.json
```
**2. Remove ALL old eslint packages first:**
```bash
npm uninstall @typescript-eslint/eslint-plugin @typescript-eslint/parser eslint
# Or with pnpm:
pnpm remove @typescript-eslint/eslint-plugin @typescript-eslint/parser eslint
```
**3. Install everything together (including TypeScript upgrade):**
`typescript-eslint` v8.x requires **TypeScript >=4.8.4** and supports up to TypeScript 6. Include TypeScript in the install to avoid ERESOLVE errors:
```bash
npm install -D typescript@5 eslint@9 typescript-eslint obsidian eslint-plugin-obsidianmd
```
> **Why include TypeScript?** If your project has TypeScript 4.7.x or older, npm will refuse to install `typescript-eslint` with `ERESOLVE unable to resolve dependency tree`. Installing TypeScript in the same command resolves this. **Do not install TypeScript 7** — it has no JavaScript API yet, so `typescript-eslint` cannot use it and npm fails with `ERESOLVE`.
**4. Remove old config files:**
```bash
rm -f .eslintrc .eslintrc.js .eslintrc.json .eslintrc.yml .eslintrc.yaml
```
**5. Verify old packages are gone:**
```bash
grep "@typescript-eslint/eslint-plugin" package.json
# Should return nothing. If it still shows, run:
npm uninstall @typescript-eslint/eslint-plugin
```
#### Why Migration Fails
The old `@typescript-eslint/eslint-plugin` and `@typescript-eslint/parser` (v5-7) conflict with the new unified `typescript-eslint` package (v8+). Common errors:
- `ERESOLVE unable to resolve dependency tree` — TypeScript too old (or TypeScript 7), or old packages still installed
- `TypeError: scopeManager.addGlobals is not a function` — version conflict between old and new packages
- `Parsing error: Unexpected character 'e' found` — parser not loading due to version mismatch
- `peer eslint@"^6.0.0 || ^7.0.0 || ^8.0.0"` warnings — old @typescript-eslint packages don't support ESLint 9+
### Version Requirements
Versions at time of writing:
- `eslint-plugin-obsidianmd` 0.6.0
- **Node.js 20.19+, 22.13+, or 24+** (Node.js 18 is no longer supported — upgrade locally and in CI)
- `eslint` 9.19+ (flat config). `defineConfig`/`globalIgnores` from `eslint/config` need 9.22+
- `typescript-eslint` 8.35.1+ (8.70.1+ recommended — fixes a `no-unnecessary-type-assertion` false positive on `{}` asserted to a `Record` alias)
- `typescript` 4.8.4+, up to 6.x. **Not TypeScript 7.**
- `obsidian` installed as a devDependency
- A `minimatch` override in `package.json` until the toolchain ships `minimatch` 11 — see [`npm audit`: moderate vulnerabilities in `minimatch`](#npm-audit-moderate-vulnerabilities-in-minimatch-ghsa-g3hv-75wg-m249)
Peer dependencies are `eslint >=9.19.0`, `typescript >=4.8.4`, and `typescript-eslint ^8.35.1`. Everything else the config needs — `@eslint/json`, `eslint-plugin-import`, `@microsoft/eslint-plugin-sdl`, `eslint-plugin-depend`, `eslint-plugin-no-unsanitized`, `eslint-comments` — ships as a dependency of the plugin, so you don't install those yourself.
**ESLint 10** works, with caveats: npm prints `ERESOLVE overriding peer dependency` warnings (three bundled plugins don't declare ESLint 10 support yet), `npm ls` reports `invalid: eslint@10…`, and installs with `strict-peer-deps` fail. ESLint 10 also adds `no-unassigned-vars`, `no-useless-assignment`, and `preserve-caught-error` at `error`. `preserve-caught-error` suggests `new Error(msg, { cause })`, which needs `ES2022` in your tsconfig `lib`. ESLint 9 is the conservative choice.
**TypeScript notes:**
- `moduleResolution: "node"` shows a deprecation warning on 5.9+ and stops `tsc` on TypeScript 6 → use `"bundler"` for esbuild projects
- `baseUrl` is deprecated (removed in TS 7.0) → remove if not using path aliases
- TypeScript 6 defaults `types` to `[]`, so `eslint.config.mts` linted via `allowDefaultProject` has no Node types and `tsconfigRootDir: import.meta.dirname` is reported by `no-unsafe-assignment`. Add `"types": ["node"]` to `compilerOptions`
## Upgrading from v0.5.1
v0.6.0 fixes findings on correct code, and fixes and suggestions that changed what correct code does or did not compile, found by linting about 10,300 community plugins. The number of findings barely changes (about 0.2% fewer). The only config change you may need is for `acronyms`.
| Change | What to do |
|--------|------------|
| `ui/sentence-case`, `ui/sentence-case-json`, `ui/sentence-case-locale-module`: `acronyms` **adds to** the built-in acronyms instead of replacing them | Drop built-in acronyms you listed again only to add one. If you used `acronyms` to leave some built-in ones out, add `replaceDefaultAcronyms: true` — see [ui-ux.md](ui-ux.md#enforce-sentence-case-for-ui-text) |
| New rule `no-await-chainable` (`error`, TypeScript files, needs type information) | Remove `await` from a `Setting` or UI component chain, and don't `return` one from an `async` function — it never settles and the app hangs. See [ui-ux.md](ui-ux.md#dont-await-a-setting-or-ui-component) |
| New rule `commands/check-callback-uses-checking` (`warn`) | Read `checking` in every `checkCallback`/`editorCheckCallback` and act only when it is `false`, or switch to `callback`/`editorCallback`. See [ui-ux.md](ui-ux.md#checkcallback-must-read-checking) |
| `--fix` changes less: `prefer-window-timers` on an `activeWindow` timer whose ID is kept or cleared, `prefer-instanceof` on a value that may be null behind a type assertion, `prefer-create-el` on a call with comments in its arguments are now suggestions | After `eslint --fix`, resolve the remaining findings by hand or accept the editor suggestion — see [Fixes vs. suggestions](#fixes-vs-suggestions-v0x) |
| `no-global-this`/`prefer-window-timers` give no fix or suggestion where TypeScript has narrowed `window` (e.g. the `else` of `if ("requestIdleCallback" in window)`) | Rewrite by hand; the old fix didn't compile (TS2339) |
| `settings-tab/no-problematic-settings-headings` reports "General" or plugin-name headings only at the top of the tab | Delete disable comments on lower "General" headings — they are now unused |
| `prefer-active-doc` offers `activeDocument.body` for an element put in `document.body` only for a moment (download link, copy textarea) | Accept the suggestion; it moves the element's `appendChild()` **and** `removeChild()`/`remove()` together |
| `worker.ts` (any extension) is treated as web worker code, like `*.worker.ts` | Delete overrides you added for it |
| Test files and tool configs get the Node globals; every `.cjs` file gets `module`/`exports` | Delete `globals.node` overrides and `no-undef` disables for `jest.config.js`, `release.config.cjs`, scripts |
| `no-nodejs-modules` reports `require?.('fs')` (the bundle's `require` exists on mobile) and a `require()` in a `try` whose `catch` always rethrows | Use `window.require?.('fs')` or a `Platform.isDesktop` guard; handle the error in the `catch` instead of rethrowing |
| `prefer-file-manager-trash-file` reports `vault.delete(file, force)` with a non-literal `force` | Use `this.app.fileManager.trashFile(file)` |
New findings are rare: besides the two new rules, `no-unsupported-api` now reports `activeDocument || document` and `if (activeDocument)` below 0.15.0 (only `typeof activeDocument` checks a global that may not exist), and a used `duplicateLeaf()` result below 0.13.8. It also recognizes more guards: `app.secretStorage?.getSecret(…)`, `?? null` fallbacks, a renamed or namespaced `requireApiVersion()`, and a `readonly` field set from it.
## Upgrading from v0.5.0
v0.5.1 needs no config change. It fixes false positives and fixes/suggestions that changed what correct code does, found by linting 600 community plugins: about 16% fewer findings overall. New findings come from two rules.
| Change | What to do |
|--------|------------|
| `prefer-instanceof` reports `e.target instanceof HTMLElement` (also `relatedTarget`, `currentTarget`, `srcElement`) | Never autofixed. Use `e.targetNode?.instanceOf(HTMLElement)` — see [below](#using-instanceof-on-an-events-target) |
| `no-unsupported-api` checks APIs with no `@since` against the first typings that declare them | Guard them or raise `minAppVersion`: `activeDocument`/`activeWindow` 0.15.0, `targetNode`/`instanceOf()`/`el.doc`/`el.win` 0.15.3, `createSvg()` 1.1.0, `setCssStyles()`/`setCssProps()`/`nextFrame()` 1.1.7, `Modal.setTitle()` 1.5.1 |
| `validate-manifest` checks `id` only with `checkId: true` | Delete an `allowedWords: { id: [...] }` entry you added for 0.5.0. Turn `checkId` on only for an unpublished plugin |
| `no-static-styles-assignment` reports at the first fixed-value property of `setCssStyles()`/`setCssProps()`, not at the call | Move an `eslint-disable-next-line` above a multi-line call to sit above that property |
| `prefer-active-doc` reports changes to `document.body`/`documentElement`/`head` with a new message and no suggestion | Apply and undo the change in each window's document — see [below](#using-document-or-window-directly) |
| Tool configs, `scripts/`, test setup files and helpers are exempt like test files | Delete overrides you added for them (see [Test, tooling and web worker files](#test-tooling-and-web-worker-files-automatic)) |
| `activeDocument.createElement()` is no longer reported by `prefer-create-el` | Delete disable comments for it — they are now reported as unused |
Rules that now report nothing below the `minAppVersion` their replacement needs: `prefer-get-language` (1.8.7), `prefer-abstract-input-suggest` (1.4.10), `prefer-file-manager-trash-file` (1.6.6), `prefer-instanceof` (0.15.0; no fix below 0.15.3), and `prefer-create-el` for each helper (`createDiv()` 0.10.0, `createSvg()` 1.1.0).
## Upgrading from v0.4.x
v0.5.0 is a breaking release that lints more files and needs newer tooling. Expect new findings, mostly from `prefer-active-doc`, `validate-manifest`, `validate-license`, `no-static-styles-assignment`, and `prefer-instanceof`. Test files no longer get the Obsidian-runtime rules and `no-undef` no longer runs on TypeScript, so most projects see fewer findings overall.
| Change | What to do |
|--------|------------|
| Node.js 18 dropped | Use Node.js 20.19+, 22.13+, or 24+ locally and in CI |
| `@eslint/json` 2 | If your config registers `@eslint/json` itself, upgrade it to 2.x — 0.14 fails with `Cannot redefine plugin "json"` |
| `obsidian` no longer installed for you | `npm install -D obsidian`, or `no-unsupported-api` reports nothing |
| `@eslint/js` no longer installed for you | If your config imports it, add it to `devDependencies` |
| `manifest.json` and `LICENSE` are now linted | Run ESLint from the project root (`eslint .`, not `eslint src`). Scope type-checked configs and rule-override blocks with `files` (see [below](#scope-overrides-with-files)) |
| `@typescript-eslint/no-misused-promises` replaced by `obsidianmd/no-misused-promises` | Rename disable comments — old ones are now reported as unused. If you layer `strictTypeChecked`/`recommendedTypeChecked`, turn the typescript-eslint rule `off` in that block |
| `@typescript-eslint/no-require-imports` is off again | Delete disable comments for it (now reported as unused) |
| `no-undef` is off for TypeScript | Delete disable comments for it in `.ts` files |
| Implied eval in TS is reported by `@typescript-eslint/no-implied-eval` only | Rename `no-implied-eval` disable comments in `.ts` files |
| `ui/sentence-case` is off | Opt back in: `"obsidianmd/ui/sentence-case": ["warn", { enforceCamelCaseLower: true }]` |
| `prefer-active-doc` now warns | Replace global `document` with `activeDocument` (or `el.doc`) |
| Desktop-only repos: raising `no-nodejs-modules` severity no longer re-enables it | Use `["error", { isDesktopOnly: false }]` |
| `ruleConfigs` hold only obsidianmd rules | If you use `ruleConfigs` without `recommended`, add `@typescript-eslint/no-deprecated` yourself; `validate-manifest`/`validate-license` need their own blocks |
**From the sample plugin's config:** `npm install -D eslint-plugin-obsidianmd@0.5` and the `eslint.config.mts` works unchanged. You can drop `'manifest.json'` from `allowDefaultProject` and `extraFileExtensions: ['.json']` — both were only needed for v0.4. Remove `'package.json'` from `globalIgnores` so `depend/ban-dependencies` checks it.
## The Complete ESLint Config
### Recommended Config (start here)
`obsidianmd.configs.recommended` is self-contained — it bundles the core `js.configs.recommended` rules of your installed ESLint, `typescript-eslint` (`recommendedTypeChecked` for `.ts`, `recommended` for `.js`), all Obsidian rules, plus `import`, `@microsoft/sdl`, `depend`, `no-unsanitized`, and `eslint-comments`, and it injects the Obsidian globals (`activeDocument`, `createDiv`, `sleep`, …). This is the same ruleset the community scanner runs.
You add two things: a `globalIgnores` entry for build output, and a `parserOptions` block so the type-checked rules can access your TypeScript project.
✅ **CORRECT** (v0.5.x):
```js
// eslint.config.mjs
import { defineConfig, globalIgnores } from "eslint/config";
import obsidianmd from "eslint-plugin-obsidianmd";
export default defineConfig([
// Build output and the sample plugin's Node build scripts are not plugin code.
globalIgnores(["node_modules", "dist", "main.js", "esbuild.config.mjs", "version-bump.mjs"]),
...obsidianmd.configs.recommended,
{
languageOptions: {
parserOptions: {
projectService: {
allowDefaultProject: ["eslint.config.*"],
},
},
},
},
]);
```
```jsonc
// package.json
"scripts": {
"lint": "eslint ."
}
```
❌ **INCORRECT**:
```js
export default defineConfig([
{ ignores: ["main.js", "*.mjs", "package.json"] }, // hides package.json from depend/ban-dependencies
...obsidianmd.configs.recommended,
{
languageOptions: {
parserOptions: {
projectService: true,
extraFileExtensions: [".json"], // only needed for v0.4
},
},
},
]);
// with "lint": "eslint src" — never visits manifest.json, LICENSE, or package.json
```
> **Run ESLint from the project root.** The recommended config matches `package.json`, `manifest.json`, and `LICENSE` (also `LICENSE.md`, `LICENSE.txt`) **by name, next to your ESLint config**. `eslint src` never visits them, so `depend/ban-dependencies`, `validate-manifest`, and `validate-license` silently do nothing. Matching is case-sensitive on every OS: `License` or `Manifest.json` is not linted. Rules that read `minAppVersion`/`isDesktopOnly` also read `manifest.json` from the working directory.
> **Ignore build output.** `main.js` is esbuild output; `esbuild.config.mjs` and `version-bump.mjs` are Node build scripts. None is in your tsconfig, so without the ignore ESLint fails on them with "was not found by the project service". If your plugin has no build step and `main.js` is your source, don't ignore it — add it to `allowDefaultProject` and declare `module`/`exports` as writable globals for it.
> **No separate parser import needed.** The recommended config bundles the typescript-eslint parser. You don't need to import `tseslint` or set `parser` yourself — just provide `parserOptions`.
> **`allowDefaultProject`** covers files in no `tsconfig.json`, such as the config file itself (the sample plugin's `eslint.config.mts` matches the recommended config's TypeScript glob).
### Plugins written in JavaScript
`.js`/`.cjs`/`.mjs`/`.jsx` files get core rules, typescript-eslint `recommended` (not type-checked), and every obsidianmd rule except the seven that need type information (`no-unsupported-api`, `no-misused-promises`, `prefer-create-el`, `prefer-file-manager-trash-file`, `prefer-instanceof`, `no-plugin-as-component`, `no-view-references-in-plugin`). A JavaScript plugin needs **no** `parserOptions` block — with it and no `jsconfig.json`, every file fails with "was not found by the project service". To enable the type-aware rules, add a `jsconfig.json` that includes your sources and a block with `files: ["src/**/*.js"]`, `extends: [tseslint.configs.recommendedTypeChecked]`, `parserOptions: { projectService: true }`, `...obsidianmd.ruleConfigs.recommendedTypeChecked`, and `"@typescript-eslint/no-misused-promises": "off"`.
### Locale checks: `recommendedWithLocalesEn`
Swap `recommended` for `recommendedWithLocalesEn` to add `ui/sentence-case-json` and `ui/sentence-case-locale-module` (both `warn`) for English locale files: JSON files and modules (`.ts`, `.js`, `.cjs`, `.mjs`) named `en`, `en-*`, `en_*`, or `en.*` (e.g. `en.json`, `en-US.ts`, `en.messages.json`, any case), or under a directory named so (`en/`, `en-US/`). `english.json`, `entries.json`, and `env.json` are not matched. Inline `ui/sentence-case` stays off in both configs.
### Customizing rules
The recommended set is opinionated, and the scanner forbids disabling certain rules inline (see "Disabling rule `X` is not allowed" below), so prefer config-level overrides over `eslint-disable` comments.
#### Scope overrides with `files`
Because v0.5.0 also lints `package.json`, `manifest.json`, and `LICENSE`, **every rule-override block needs a `files` glob for your source.** The `@typescript-eslint`, `import`, and other bundled plugins are registered for JS/TS files only.
✅ **CORRECT**:
```js
export default defineConfig([
globalIgnores(["node_modules", "dist", "main.js", "esbuild.config.mjs", "version-bump.mjs"]),
...obsidianmd.configs.recommended,
{
languageOptions: {
parserOptions: {
projectService: { allowDefaultProject: ["eslint.config.*"] },
},
},
},
{
files: ["**/*.{ts,cts,mts,tsx,js,cjs,mjs,jsx}"],
rules: {
"obsidianmd/sample-names": "off",
"obsidianmd/ui/sentence-case": ["warn", { enforceCamelCaseLower: true }], // opt in; off by default
"@typescript-eslint/no-unused-vars": ["error", { args: "after-used" }],
},
},
]);
```
❌ **INCORRECT** — no `files`, so the block reaches `manifest.json`/`LICENSE` and stops the run:
```js
{
rules: {
"@typescript-eslint/no-unused-vars": ["error", { args: "after-used" }],
},
}
// A configuration object specifies rule "@typescript-eslint/no-unused-vars",
// but could not find plugin "@typescript-eslint".
```
The parser-options block and `linterOptions` are meant for every file and stay unscoped.
#### Layering stricter typescript-eslint configs
Scope `strictTypeChecked`/`stylisticTypeChecked` to TypeScript files, and turn back off the two rules they re-enable that conflict with this plugin:
✅ **CORRECT**:
```js
import tseslint from "typescript-eslint";
// after ...obsidianmd.configs.recommended:
{
files: ["**/*.ts"],
extends: [tseslint.configs.strictTypeChecked, tseslint.configs.stylisticTypeChecked],
rules: {
// obsidianmd/no-misused-promises replaces it; both on = every Promise reported twice,
// and Obsidian's chaining `then` (Setting, components) flagged again.
"@typescript-eslint/no-misused-promises": "off",
// Conflicts with the Platform.isDesktop-guarded require() that no-nodejs-modules asks for.
"@typescript-eslint/no-require-imports": "off",
},
},
```
❌ **INCORRECT** — unscoped, so it reaches `LICENSE` and aborts with "You have used a rule which requires type information":
```js
...obsidianmd.configs.recommended,
...tseslint.configs.strictTypeChecked,
```
`strictTypeChecked` also turns `@typescript-eslint/require-await`, `ban-ts-comment`, and `prefer-const` back on, which the recommended config leaves off. `require-await` reports an `async onOpen()`/`onClose()` that never awaits.
#### Disabling rules for non-plugin files
ESLint has no `"obsidianmd/*": "off"`. Use `ruleConfigs` to generate the overrides:
```js
{
files: ["scripts/**"],
rules: Object.fromEntries([
...Object.keys(obsidianmd.ruleConfigs.recommended),
...Object.keys(obsidianmd.ruleConfigs.recommendedTypeChecked),
].map(rule => [rule, "off"])),
}
```
For code that only runs on desktop but has no manifest (a CLI, tooling), scope the `isDesktopOnly` option instead of disabling the rule: `{ files: ["cli/**"], rules: { "obsidianmd/no-nodejs-modules": ["warn", { isDesktopOnly: true }] } }`.
#### Test, tooling and web worker files (automatic)
The recommended config exempts test, tooling and worker files from the rules about code running inside Obsidian — you don't need overrides for the standard paths:
- **Test files** — `**/*.{test,tests,spec,specs,e2e,setup,testing}.*`, `**/testUtils*`, anything under `test/`, `tests/`, `__tests__/`, `mocks/`, `__mocks__/`, `e2e/`, `e2e-tests/`, `test-helpers/`, `test_helpers/`, `test-support/`, `test-utils/`, `test_utils/`, top-level `automation/` or `test-vault/`, test runner setup files (`**/test-setup.*`, `**/setupTests.*`, `**/global-setup.*`, `**/*-global-setup.*`), and `wdio.conf.*`, `playwright.config.*`.
- **Tooling files** (v0.5.1) — configs named after their tool (`eslint.config.*`, `vite.config.*`, `vitest.config.*`, `jest.config.*`, `rollup.config.*`, `esbuild.config.*`, `webpack.config.*`, `svelte.config.*`, `postcss.config.*`, `tailwind.config.*`, and others; also `vitest.*.config.*` and `.eslintrc.*`/`.prettierrc.*`), `esbuild.*`, `version-bump.*`, and anything under `scripts/`. A plugin's own `config.ts` or `settings.config.ts` is **not** a tooling file.
- **Web worker files** — `**/worker.*` (v0.6.0), `**/*.worker.*`, `**/*-worker.*`, `**/*_worker.*` (v0.5.1), and anything under `workers/` (not `worker/`, which may hold the main-thread code that starts the worker). Worker globals replace the browser/Obsidian ones.
Since v0.6.0, test and tooling files also get the **Node globals** (`process`, `__dirname`, `module`), even in a plugin that isn't desktop-only, and every `.cjs` file gets `module` and `exports` — so `module.exports` in `jest.config.js` or `release.config.cjs` is no longer reported by `no-undef`.
| Rule | Test & tooling files | Worker files |
|------|---------------------|--------------|
| `no-global-this`, `prefer-active-doc`, `prefer-create-el`, `prefer-instanceof`, `prefer-window-timers`, `platform` | off | off |
| `no-nodejs-modules`, `no-tfile-tfolder-cast`, `hardcoded-config-path`, `no-unsupported-api`, `regex-lookbehind`, `no-forbidden-elements`, `no-static-styles-assignment`, `prefer-file-manager-trash-file`, `prefer-get-language` | off | on |
| `rule-custom-message` | `no-new-func` only — `console.log` is allowed | full |
Security rules, including `no-new-func`, still apply everywhere. Still ignore the sample plugin's `esbuild.config.mjs` and `version-bump.mjs` in `globalIgnores`: they are in no `tsconfig.json`, so otherwise they need `allowDefaultProject`.
For tests or tooling under other names (e.g. `integration-tests/`, `tools/`), add the same `"off"` overrides for that path or put it in `globalIgnores`. To allow `console` there without losing `no-new-func`, restate `rule-custom-message` with only its `no-new-func` entry:
❌ **INCORRECT** — also drops the `Function`-constructor check:
```js
{ files: ["tools/**"], rules: { "obsidianmd/rule-custom-message": "off" } }
```
✅ **CORRECT**:
```js
{
files: ["tools/**"],
rules: {
"obsidianmd/rule-custom-message": ["error", {
"no-new-func": {
messages: {
"The Function constructor is eval": "Using the `Function` constructor is dangerous because it executes arbitrary code, similar to `eval()`",
},
},
}],
},
}
```
#### Manifest options
Since v0.5.1, `validate-manifest` checks the `id` (no "obsidian", not ending in "plugin") **only** with `checkId: true`. A published plugin's id can never change and the scanner doesn't check it, so leave `checkId` off once you've submitted. Turn it on for a plugin you haven't submitted yet. Options live in a block scoped to the manifest (a JSON manifest can't carry a disable comment):
❌ **INCORRECT** — a published plugin; `allowedWords.id` does nothing without `checkId` since v0.5.1:
```js
{
files: ["manifest.json"],
rules: {
"obsidianmd/validate-manifest": ["warn", { allowedWords: { id: ["obsidian"] } }],
},
}
```
✅ **CORRECT** — an unsubmitted plugin, so its id can still change:
```js
{
files: ["manifest.json"],
rules: {
"obsidianmd/validate-manifest": ["warn", { checkId: true }],
},
}
```
`ignore: ["noForbiddenWords"]` or `["descriptionFormat"]` skips a check group entirely.
### Using only obsidianmd rules (without the full config)
The plugin exports `ruleConfigs` with two presets you can spread into a `rules` block:
- `obsidianmd.ruleConfigs.recommended` — obsidianmd rules that do not require type information
- `obsidianmd.ruleConfigs.recommendedTypeChecked` — obsidianmd rules that require type information (includes `obsidianmd/no-misused-promises`)
As of v0.5.0 they hold **only** obsidianmd rules for source files: `@typescript-eslint/no-deprecated` moved out, and so did `validate-manifest`/`validate-license` (they need their own `files`/`language` blocks).
```js
import obsidianmd from "eslint-plugin-obsidianmd";
{
files: ["**/*.ts"],
extends: [tseslint.configs.recommendedTypeChecked],
plugins: { obsidianmd },
rules: {
...obsidianmd.ruleConfigs.recommended,
...obsidianmd.ruleConfigs.recommendedTypeChecked,
"@typescript-eslint/no-misused-promises": "off", // replaced by obsidianmd/no-misused-promises
"@typescript-eslint/no-deprecated": "warn", // no longer in ruleConfigs
},
}
```
With `ruleConfigs` instead of `configs.recommended`, you must declare Obsidian globals (`activeDocument`, `activeWindow`, `createEl`, `sleep`, etc.) yourself; test, tooling, and worker files are not exempted (and `rule-custom-message` keeps `no-console` there); third-party plugins (`@microsoft/sdl`, `import`, `no-unsanitized`, `depend`, `eslint-comments`) are not included; and `manifest.json`/`LICENSE` need their own blocks (`language: "json/json"` with `@eslint/json` 2.x, and `language: "obsidianmd/plain-text"`). Most users should stick with `configs.recommended`.
### Default severities (v0.6.0)
Most Obsidian rules are **`warn`** (warnings are publicly visible on your Scorecard, so fix them too). These are the exceptions:
| Severity | Rules |
|----------|-------|
| **`error`** | `detach-leaves`, `no-await-chainable` (v0.6.0), `no-forbidden-elements`, `no-misused-promises`, `no-plugin-as-component`, `no-sample-code`, `no-static-styles-assignment`, `no-unsupported-api`, `no-view-references-in-plugin`, `platform`, `regex-lookbehind`, `rule-custom-message`, `sample-names`, `settings-tab/no-manual-html-headings`, `settings-tab/no-problematic-settings-headings` |
| **`off`** | `ui/sentence-case` (opt in manually) |
| **`warn`** | everything else — `commands/*` (including `commands/check-callback-uses-checking`, v0.6.0), `editor-drop-paste`, `hardcoded-config-path`, `no-global-this`, `no-nodejs-modules`†, `no-tfile-tfolder-cast`, `object-assign`, `prefer-abstract-input-suggest`, `prefer-active-doc`, `prefer-create-el`, `prefer-file-manager-trash-file`, `prefer-get-language`, `prefer-instanceof`, `prefer-window-timers`, `validate-license`, `validate-manifest`, `vault/iterate`, all four `settings-tab/*` declarative rules, and (in `recommendedWithLocalesEn`) the two locale sentence-case rules |
† `no-nodejs-modules` reads your `manifest.json`: it reports nothing when `"isDesktopOnly": true` (only a literal `true` counts). Override with the `isDesktopOnly` option.
### Fixes vs. suggestions (v0.x)
`--fix` applies a rewrite only where it can't break type-checking. Elsewhere the same rewrite is an **editor suggestion** (💡) — review and apply it in your editor; `--fix` never applies suggestions. Rules that only reported now offer suggestions: `prefer-active-doc`, `prefer-file-manager-trash-file`, `prefer-get-language`, `object-assign`, `vault/iterate`, the `commands/*` rules, and `no-default-hotkeys`. Suggestions that need a newer Obsidian than your `minAppVersion` are not offered (`activeDocument` 0.15.0, `instanceOf()` 0.15.3, `getFileByPath()` 1.5.7, `trashFile()` 1.6.6, `getLanguage()` 1.8.7). Where no `minAppVersion` is known, `prefer-instanceof` and `prefer-create-el` still fix, and the suggestion names the version it needs. Renaming a command ID breaks users' hotkeys, `executeCommandById()` calls, `obsidian://` URIs, and other plugins that use the old ID — think before accepting that suggestion.
v0.6.0 moves more rewrites from `--fix` to suggestions, because they changed what correct code does: an `activeWindow` timer whose ID is kept or cleared (`prefer-window-timers`), an `instanceof` check on a value that may be `null` behind a cast (`prefer-instanceof` — the fix turned a `false` check into one that throws), a call with comments inside its arguments (`prefer-create-el`, `prefer-instanceof`), and a timer or `globalThis` in a function the file turns into a string for an inline worker. Where TypeScript has narrowed `window`, `no-global-this` and `prefer-window-timers` offer nothing. `settings-tab/no-problematic-settings-headings` no longer removes a heading below the top of the tab. Expect a few more findings left after `eslint --fix`.
❌ **INCORRECT** — assuming `--fix` resolved everything, and committing:
```bash
npx eslint . --fix && git commit -am "lint"
```
✅ **CORRECT** — re-run without `--fix` and resolve what's left (apply 💡 suggestions in your editor):
```bash
npx eslint . --fix
npx eslint .
```
### Why type-aware linting matters (now bundled)
The recommended config already extends `typescript-eslint`'s **`recommendedTypeChecked`** for `.ts` files, so you get the type-aware rules automatically:
| Config | Type-aware | What it catches |
|--------|-----------|-----------------|
| `recommended` | No | Basic TS issues (no-explicit-any, etc.) |
| `recommendedTypeChecked` | Yes | + no-floating-promises, restrict-template-expressions, no-unnecessary-type-assertion, await-thenable, no-base-to-string (`no-misused-promises` is swapped for `obsidianmd/no-misused-promises`) |
| `strictTypeChecked` | Yes | + no-unsafe-assignment, no-unsafe-member-access, no-unsafe-return, no-unsafe-call |
The only thing you must supply is `parserOptions.projectService` (or `project`) so these rules can load type information — without it ESLint throws "you have used a rule which requires type information".
> **Tip:** The recommended config runs `@typescript-eslint/no-deprecated` (`warn`), which catches deprecated Obsidian APIs (e.g., `setWarning()` → `setDestructive()` in 1.13+). This only works when the `obsidian` devDependency typings are current — stale typings silently hide deprecations. Keep `"obsidian": "latest"` in your `package.json`. While `minAppVersion` is below 1.13.0 it allows `display()`, which a settings tab must still call there.
## tsconfig.json Requirements
The type-checked rules need `project` in parser options, which means your `tsconfig.json` must cover all linted files:
```json
{
"compilerOptions": {
"module": "ESNext",
"target": "ES6",
"moduleResolution": "bundler",
"strictNullChecks": true,
"lib": ["DOM", "ES5", "ES6", "ES7"]
},
"include": ["src/**/*.ts"]
}
```
> **TypeScript 5.9+ users:** Use `"bundler"` for projects using esbuild/bundlers. The `"node10"` option is deprecated and will be removed in TS 7.0. Also remove `"baseUrl"` if you're not using path aliases — it's deprecated.
> **Note:** For bundler projects (esbuild), omit `outDir` entirely — the bundler handles output. Setting `outDir: "./"` causes TypeScript to auto-exclude the project root, breaking type checking.
If you get "file not found in project" errors from ESLint, your `include` pattern doesn't match your source files.
### Strict mode recommendation
For new projects, enable full strict mode to catch more issues at compile time:
```json
{
"compilerOptions": {
"strict": true
}
}
```
If migrating an existing project, be aware that your IDE may use stricter settings than your tsconfig. Running `tsc --noEmit --strict` locally catches what the IDE sees.
The patterns in this guide (Events callbacks, Setting callbacks) work correctly with strict mode enabled.
### TS2564: Property has no initializer
**Error:** `Property 'foo' has no initializer and is not definitely assigned in the constructor.`
This occurs when `strictPropertyInitialization` is enabled (part of `strict` mode). Common scenario: your tsconfig only has `strictNullChecks: true`, but your IDE applies full strict mode.
**Fix patterns:**
```typescript
// Pattern A: Definite assignment assertion (when assigned in onload/lifecycle)
export class MyPlugin extends Plugin {
settings!: MySettings; // ! tells TS "I'll assign this before use"
async onload() {
this.settings = await this.loadData();
}
}
// Pattern B: Initialize with undefined-compatible type
export class MyModal extends Modal {
result: string | undefined; // Explicitly allow undefined
}
// Pattern C: Initialize with default value
export class MyView extends ItemView {
wrapperEl: HTMLElement = createDiv();
}
```
**When to use each:**
- **Pattern A (`!`)**: Property assigned in `onload()`, `onOpen()`, or similar lifecycle method. Most common for plugin settings.
- **Pattern B (`| undefined`)**: Property may legitimately be unset. Requires null checks when accessing.
- **Pattern C (default value)**: Property has a sensible default. Use when the default is cheap to create.
**Debugging IDE vs build mismatch:**
```bash
# See what strict mode catches (matches most IDEs)
tsc --noEmit --strict
# Compare against your actual tsconfig
tsc --noEmit
```
If errors appear in IDE but build succeeds, either enable `strict: true` in tsconfig or apply the fix patterns above.
## Common Violations and How to Fix Them
### Loading Node.js modules (`require()` vs `import`)
**Rules:** `obsidianmd/no-nodejs-modules` (`warn`); `@typescript-eslint/no-require-imports` is **off** in v0.5.0
Node.js modules (`fs`, `path`, `os`, etc.) exist only on desktop. In a plugin that isn't `isDesktopOnly`, a static `import` of a Node built-in is always reported — it loads the module wherever the file runs and can't be guarded. Load it with a dynamic `import()` or a `require()` inside a `Platform.isDesktop` guard:
```typescript
// Bad — static import loads on mobile too (reported by no-nodejs-modules)
import * as fs from 'fs';
// Good — guarded dynamic import
if (Platform.isDesktop) {
const fs = await import('fs');
}
// Also good — guarded require (no-require-imports is off, so no disable comment needed)
if (Platform.isDesktop) {
const fs = require('fs') as typeof import('fs');
}
```
In a desktop-only plugin (`"isDesktopOnly": true` in `manifest.json`), top-level `import * as fs from 'fs'` is fine — esbuild converts it to `require()` in the CJS bundle. If you previously had `// eslint-disable-next-line @typescript-eslint/no-require-imports`, delete it: v0.5.0 reports it as an unused directive.
For `electron`, add a minimal type declaration file since `@types/electron` is not typically installed:
```typescript
// src/electron.d.ts
declare module 'electron' {
const remote: { dialog: Dialog } | undefined;
// ... only the types you actually use
}
```
Then import normally:
```typescript
import * as electron from 'electron';
```
### Unexpected control character in regular expression: `\x1b`
**Rule:** `no-control-regex`
ANSI escape parsing requires the ESC character in regex. Use the `RegExp` constructor instead of a literal:
```typescript
// Bad
const re = /\x1b\[[\d;]*m/g;
// Good
const re = new RegExp('\\x1b\\[[\\d;]*m', 'g');
```
### `value` will use Object's default stringification format
**Rule:** `@typescript-eslint/no-base-to-string` / `@typescript-eslint/restrict-template-expressions`
When accessing `Record<string, unknown>` values (common with tool inputs from JSONL), `String(value)` or template literals can produce `[object Object]`:
```typescript
// Bad — value is unknown, String() on an object gives [object Object]
const filePath = String(block.input['file_path'] || '');
// Good — type-narrow first
const filePath = typeof block.input['file_path'] === 'string'
? block.input['file_path']
: '';
```
### Promises must be awaited
**Rule:** `@typescript-eslint/no-floating-promises`
Fire-and-forget promises need explicit `void`:
```typescript
// Bad
MarkdownRenderer.render(app, md, el, '', component);
navigator.clipboard.writeText(text);
this.app.workspace.revealLeaf(leaf);
// Good
void MarkdownRenderer.render(app, md, el, '', component);
void navigator.clipboard.writeText(text);
void this.app.workspace.revealLeaf(leaf);
```
### Promise returned where void expected
**Rule:** `obsidianmd/no-misused-promises` (`error`; replaced `@typescript-eslint/no-misused-promises` in v0.5.0)
Same as typescript-eslint's rule, except Obsidian's chaining `then` (on `Setting` and components) no longer counts as a Promise — so returning a `Setting` chain from a callback is no longer a false positive. Real Promises are still reported. `async onload()` in a `Plugin` subclass is fine (v0.5.1 also accepts it with `obsidian` typings older than 1.7.2); `async onunload()` is still reported, because Obsidian doesn't await it. Async callbacks in `addEventListener` or other void-expecting contexts:
```typescript
// Bad
btn.addEventListener('click', async () => {
await doSomething();
});
// Good — wrap in void IIFE
btn.addEventListener('click', () => {
void (async () => {
await doSomething();
})();
});
// Also good — just void the promise
btn.addEventListener('click', () => {
void doSomething();
});
```
Unlike other `obsidianmd/*` rules, this one may be disabled inline. Use the new name — a disable comment naming `@typescript-eslint/no-misused-promises` still suppresses the finding but is reported as an unused directive, and `eslint --fix` deletes it:
```typescript
// Bad — reported as unused directive in v0.5.0
// eslint-disable-next-line @typescript-eslint/no-misused-promises -- handler catches its own errors
// Good
// eslint-disable-next-line obsidianmd/no-misused-promises -- handler catches its own errors
```
### Async function has no `await` expression
**Rule:** `@typescript-eslint/require-await`
Note: `eslint-plugin-obsidianmd` **disables** this rule in its recommended config. The community scanner may still flag it. If your function doesn't need `await`, remove `async`:
```typescript
// Bad
async function listFiles(): Promise<string[]> {
return fs.readdirSync(dir); // sync operation, no await
}
// Good
function listFiles(): string[] {
return fs.readdirSync(dir);
}
```
For interface overrides (like `ItemView.onOpen()`) that require `Promise<void>` return type but have no async work:
```typescript
onOpen(): Promise<void> {
// ... sync setup ...
return Promise.resolve();
}
```
### This assertion is unnecessary
**Rule:** `@typescript-eslint/no-unnecessary-type-assertion`
After `instanceof` or `Array.isArray()`, TypeScript narrows the type automatically:
```typescript
// Bad
if (view instanceof TimelineView) {
(view as TimelineView).doSomething(); // cast is redundant
}
// Good
if (view instanceof TimelineView) {
view.doSomething();
}
```
For `querySelectorAll` results, use the generic form instead of casting:
```typescript
// Bad
const els = el.querySelectorAll('.my-class') as NodeListOf<HTMLElement>;
// Good
const els = el.querySelectorAll<HTMLElement>('.my-class');
```
### Disabling rule `X` is not allowed
The recommended config forbids `eslint-disable` comments for certain rules via the bundled `eslint-comments/no-restricted-disable` rule, which covers `obsidianmd/*` (**except** `obsidianmd/no-misused-promises`), `no-console`, `no-restricted-globals`, `@typescript-eslint/no-restricted-imports`, `no-alert`, `@typescript-eslint/no-deprecated`, `@typescript-eslint/no-explicit-any`, `no-eval`, `@microsoft/sdl/no-document-write`, `@microsoft/sdl/no-inner-html`, and `obsidianmd/no-nodejs-modules`. Fix the underlying issue instead of suppressing it — or, where a finding can never be acted on, use a config-level override (see [Customizing rules](#customizing-rules)). The scanner enforces these for newly submitted plugins at `error`.
Locally, unused disable directives are reported as errors (`reportUnusedDisableDirectives`). v0.5.0 turned off or renamed several rules, so these old comments now fail as unused: `@typescript-eslint/no-misused-promises` (rename to `obsidianmd/no-misused-promises`), `@typescript-eslint/no-require-imports` (delete), `no-undef` in `.ts` files (delete), and `no-implied-eval` in `.ts` files (rename to `@typescript-eslint/no-implied-eval`).
### ESLint directive comments require descriptions
All `eslint-disable` comments must include a `-- description` explaining why the suppression is necessary. Directives without descriptions produce warnings.
```typescript
// Bad — triggers "Unexpected undescribed directive comment"
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const value = obj.field!;
// Good
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- Guaranteed by earlier null check in parseConfig
const value = obj.field!;
```
This applies to all directive forms: `eslint-disable`, `eslint-disable-next-line`, and `eslint-disable-line`.
### Unsafe assignment of `any` value
**Rule:** `@typescript-eslint/no-unsafe-assignment`
Common with `JSON.parse()`. Add a type assertion:
```typescript
// Bad
const data = JSON.parse(raw);
// Good
interface MyData { field: string; count: number }
const data = JSON.parse(raw) as MyData;
```
### Unexpected console statement
**Rule:** `no-console`
Only `console.warn`, `console.error`, and `console.debug` are allowed. Use `console.debug` instead of `console.log` or `console.info`.
### Using `document` or `window` directly
**Rule:** `obsidianmd/prefer-active-doc` (`warn` as of v0.5.0 — it was `off` through v0.4.2)
For popout window compatibility, use `activeDocument` (or an element's own `el.doc`) instead of the global `document`:
```typescript
// Bad
const hit = document.querySelector('.my-plugin');
window.addEventListener('resize', onResize); // not linted, but leaks across popouts
// Good
const hit = containerEl.doc.querySelector('.my-plugin'); // the element's own document
this.registerDomEvent(activeWindow, 'resize', onResize);
```
The rule reports only the bare global `document` — not `window`, `window.document`, type positions, property names, or local bindings named `document`. It has **no autofix**: it offers an editor suggestion (`document` → `activeDocument`), because whether code should follow the focused window or a specific element's window depends on what it does. `document.contains(el)` suggests `el.isConnected` instead. No suggestion is offered after an environment check (`typeof document`), where `document` is compared (`e.target === document`) or handed on as a value (an argument, array element, assignment, return), for `document.dispatchEvent()`, or when `minAppVersion` is below 0.15.0. Test, tooling and web worker files are exempt.
Not reported (v0.5.1): `document` in a listener on the main window's `document` or `window` (it handles that window's events, so its `document` is right), `document` as the fallback to `activeDocument` (`activeDocument ?? document`), `document` listed with other documents (`[document, ...popoutDocs]`), and lookups of UI only the main window has (`status-bar`, `workspace-ribbon`, `side-dock-ribbon`, `mod-left-split`, `mod-right-split`).
**State of the whole window (v0.5.1).** A lasting change to the main window's `<body>`, `<html>`, or `<head>` — a class, attribute, CSS variable, or appended `<style>` — is reported with its own message and **no suggestion**. `activeDocument` would change whichever window has focus, so a class added in one window could be removed from another and left behind. Apply the change, and undo it, in every window's document:
```typescript
// Bad — main window only; popouts never get the class
document.body.addClass('my-plugin-on');
// Bad — whichever window has focus at onload/onunload; may add and remove in different windows
activeDocument.body.addClass('my-plugin-on');
activeDocument.body.removeClass('my-plugin-on');
// Good — every window, now and later; undone in exactly the documents it touched
private styledDocs = new Set<Document>();
private styleDoc(doc: Document) {
doc.body.addClass('my-plugin-on');
this.styledDocs.add(doc);
}
onload() {
this.app.workspace.onLayoutReady(() => {
this.styleDoc(this.app.workspace.containerEl.doc); // main window
this.app.workspace.iterateAllLeaves((leaf) => this.styleDoc(leaf.view.containerEl.doc)); // open popouts
});
this.registerEvent(this.app.workspace.on('window-open', (win) => this.styleDoc(win.doc)));
}
onunload() {
for (const doc of this.styledDocs) doc.body.removeClass('my-plugin-on');
this.styledDocs.clear();
}
```
Prefer a scoped class on your own container (`this.containerEl.addClass(...)`) when the styling only affects your view — then no window-wide state is needed.
**An element in `<body>` for a moment (v0.6.0).** An element the code appends to `document.body` and also removes — a download link, a textarea for copying text — is not window-wide state. The rule offers `activeDocument.body` and rewrites **every** `document.body` call for that element at once (`appendChild()` with `removeChild()`/`contains()`, even in a `finally`), so it is added to and removed from the same window. Moving only the `appendChild()` threw `NotFoundError` from the `removeChild()` in a popout. Capture the document once:
```typescript
// Bad — main window only; or, after a partial rewrite, appended to one window and removed from another
const a = document.createElement('a');
a.href = url; a.download = name;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
// Good — one document for the whole lifetime of the element
const doc = activeDocument;
const a = doc.body.createEl('a', { href: url, attr: { download: name } });
a.click();
a.remove();
```
An element that is never removed, and anything put in `document.head`, are still reported as window-wide state.
`document.createElement()` and the other calls `prefer-create-el` reports are left to that rule in type-checked TypeScript files, so they aren't reported twice.
`prefer-active-doc` deliberately skips `window.setTimeout()`, `window.setInterval()`, and related timer calls. Timers belong on `window`, not `activeWindow` — see `prefer-window-timers` below.
**Caution:** `activeDocument`/`activeWindow` are dynamic getters that follow window focus — two calls may return different objects. Capture the value in a variable when the same document is needed later (e.g., listener cleanup), or use `registerDomEvent()`, which captures the target at registration. The linter does not catch this; see [memory-management.md](memory-management.md) for the full pattern.
### Using bare `setTimeout`/`setInterval`
**Rule:** `obsidianmd/prefer-window-timers` (named `prefer-active-window-timers` before v0.4.0)
```typescript
// Bad
setTimeout(() => {}, 100);
setInterval(() => {}, 1000);
activeWindow.setTimeout(() => {}, 100); // also flagged
// Good
window.setTimeout(() => {}, 100);
window.setInterval(() => {}, 1000);
```
The rule covers `setTimeout`, `setInterval`, `clearTimeout`, `clearInterval`, `requestAnimationFrame`, and (v0.5.0) `cancelAnimationFrame`. Locally declared functions with those names are not flagged, and test, tooling, and web worker files are exempt.
**Exception (v0.5.1):** `activeWindow.requestAnimationFrame()` and `activeWindow.cancelAnimationFrame()` are **not** reported. A frame callback runs when its own window paints, and a hidden or minimized main window doesn't paint — so `window.requestAnimationFrame()` would stall a popout's animation until the main window is shown. Keep the cancel on the same window as the request.
**Fix vs. suggestion (v0.5.0):** with `@types/node` installed, bare `setTimeout()` returns `NodeJS.Timeout`, while `window.setTimeout()` returns `number`. So `--fix` rewrites only where no type can change — a discarded `setTimeout()`/`setInterval()` result, a `clear*()` with a `number` argument, bare `requestAnimationFrame()`/`cancelAnimationFrame()`, and `activeWindow.setTimeout()`-style calls. A stored timer gets a suggestion instead; change its type to `number` when you accept it:
```typescript
// Bad — reported, suggestion only (fixing would break a NodeJS.Timeout field)
private timer: NodeJS.Timeout = setTimeout(save, 1000);
// Good
private timer: number = window.setTimeout(save, 1000);
```
No fix is offered where `window` is shadowed (e.g. a Playwright page named `window`) or after a check showing the code may run without a window (`typeof window === "undefined"`). Since v0.6.0, neither is offered where TypeScript has narrowed `window` to a type without the timer — the `else` of `if ("requestIdleCallback" in window)`, or code after `if ("requestIdleCallback" in window) return;` — because `window.setTimeout()` there doesn't compile (TS2339). `no-global-this` behaves the same.
**Set and clear on the same window (v0.6.0).** A timer ID belongs to the window that set it. `activeWindow.setTimeout()` whose ID is kept (`this.id = activeWindow.setInterval(…)`) and `activeWindow.clearTimeout(id)`/`clearInterval(id)` now get a **suggestion**, not an autofix: fixing only one side left the timer set on one window and cleared on another, so it might never be cleared. Accept the suggestion for the set and the clear together. A timer whose ID nothing can keep — `new Promise((resolve) => activeWindow.setTimeout(resolve, ms))` — is still fixed.
```typescript
// Bad — after a partial fix: set on the main window, cleared on whichever window has focus
this.poll = window.setInterval(refresh, 5000);
activeWindow.clearInterval(this.poll);
// Good — both on window
this.poll = window.setInterval(refresh, 5000);
window.clearInterval(this.poll);
```
### Obsidian Events callback typing
**Rule:** Strict mode incompatibility with `Events.on()` callbacks
The Obsidian `Events` class (used by `Plugin`, `Component`, custom event emitters) has this signature:
```typescript
on(name: string, callback: (...data: unknown[]) => unknown, ctx?: unknown): EventRef
```
Inline typed parameters fail with strict mode:
```typescript
// Bad — strict mode error
this.peerManager.on('transfer-request', (data: { files: File[] }) => {
// TS2345: Type '(data: { files: File[] }) => void' is not assignable...
});
// Good — cast inside the callback
this.peerManager.on('transfer-request', (rawData) => {
const data = rawData as { files: File[] };
// use data.files
});
```
For simple pass-through (just re-emitting), no cast needed:
```typescript
// Good — trigger accepts unknown
peer.on('file-received', (data) => {
this.trigger('file-received', data);
});
```
### Setting component callback typing
Obsidian's `Setting` component callbacks (`Dropdown.onChange`, `Toggle.onChange`, etc.) expect generic signatures:
```typescript
// Dropdown.onChange expects (value: string) => any
// Toggle.onChange expects (value: boolean) => any
```
Using narrower types inline fails:
```typescript
// Bad — strict mode error
.onChange(async (value: 'auto' | 'manual') => {
this.settings.mode = value;
});
// Good — cast inside
.onChange(async (value) => {
const mode = value as 'auto' | 'manual';
this.settings.mode = mode;
});
```
### Detecting user language incorrectly
**Rule:** `obsidianmd/prefer-get-language`
Obsidian provides `getLanguage()` to detect the user's language setting. Don't use `localStorage` or third-party i18n detection libraries:
```typescript
// Bad
const lang = localStorage.getItem('language');
import LanguageDetector from 'i18next-browser-languagedetector';
// Good
import { getLanguage } from 'obsidian';
const lang = getLanguage();
```
### Using native DOM methods instead of Obsidian helpers
**Rule:** `obsidianmd/prefer-create-el` (`warn`; needs type information)
Obsidian provides DOM helper methods that are cleaner and more consistent. The most popout-safe form is to create the element **on a parent** that already lives in the right window:
```typescript
// Bad
const div = document.createElement('div');
const frag = document.createDocumentFragment();
const p2 = activeWindow.createEl('p'); // TS2339: 'createEl' does not exist on type 'Window'
// Good
const div2 = containerEl.createDiv({ cls: 'my-class' }); // child of an element in the right window
const p3 = containerEl.createEl('p');
const div = createDiv(); // detached, global helper
const frag = createFragment();
const p = activeDocument.createElement('p'); // detached, in the focused window's document
```
**`activeWindow.createEl()` does not compile.** Obsidian's typings declare `activeWindow` (and `el.win`, `doc.win`) as a plain `Window`; the DOM helpers are declared only as globals and on `Node`/`HTMLElement`. Since v0.5.1, `activeDocument.createElement()` and `el.doc.createElement()` are **not reported** — they are the right calls for a detached element in a popout window's document ([#240](https://github.com/obsidianmd/eslint-plugin/issues/240)). Don't use `activeDocument.createEl()` either: `createEl()` on a node appends to it, and a document takes no second root element. When a parent is at hand, a parent-element helper is still simplest (`containerEl.createEl('p')`).
What `--fix` does: global `document.createElement('p')` → `createEl('p')` and `createEl('div')` → `createDiv()` are fixed when the types prove the helper exists; tag names typed as plain `string`, custom elements, and deprecated tags are reported with no fix. A replacement that needs a newer Obsidian than your `minAppVersion` is not reported (`createDiv()`/`createSpan()` 0.10.0, `createSvg()` 1.1.0). Elements created in an iframe's document (`iframe.contentDocument`) and code inside a function named after a helper (a polyfill or test fake) are not reported. Test, tooling, and web worker files are exempt.
### Using `instanceof` on an event's target
**Rule:** `obsidianmd/prefer-instanceof` (`warn`; needs type information)
Every window has its own constructors, so a node from a popout is never `instanceof` the main window's `HTMLElement`. Since v0.5.1 the rule also reports `instanceof` on an event's `target`, `relatedTarget`, `currentTarget`, or `srcElement` — a handler in a view, modal, menu, or editor extension otherwise takes the wrong branch in a popout:
```typescript
// Bad — false for any element of a popout window
this.registerDomEvent(el, 'click', (e) => {
if (!(e.target instanceof HTMLElement)) return;
e.target.closest('.icon');
});
// Good — Obsidian's targetNode is the same value as target, typed Node | null
this.registerDomEvent(el, 'click', (e) => {
if (!e.targetNode?.instanceOf(HTMLElement)) return;
e.targetNode.closest('.icon');
});
```
Event-target checks are **never autofixed**: an `EventTarget` may be a window (the target of `focus`/`resize` on `window`), which has no `instanceOf()`, and the check narrows `e.target` for later code. For mouse, pointer, drag, touch, wheel, keyboard, input, and composition events the editor suggests `e.targetNode?.instanceOf(…)` and rewrites the other `e.target` reads in the function to match. For `FocusEvent`, plain `Event`, and `currentTarget`, it only reports. `targetNode` and `instanceOf()` need `minAppVersion` 0.15.3.
Not reported: checks against a constructor from the node's own window (`el.ownerDocument.defaultView?.HTMLElement`, also held in a `const`), `instanceof` inside an `instanceOf()` polyfill, and React's synthetic events.
### Using Node.js modules without platform guard
**Rule:** `obsidianmd/no-nodejs-modules`
Node.js built-in modules (`fs`, `path`, `os`, etc.) are only available on desktop. Guard imports with `Platform.isDesktop`:
> This rule reads your `manifest.json`: it reports nothing when `"isDesktopOnly": true` (only a literal `true` counts — `"false"` or `1` keeps it reporting). In a desktop-only repo, raising its severity does **not** turn it back on; use `["error", { isDesktopOnly: false }]`. For tooling or a CLI with no manifest, scope `["warn", { isDesktopOnly: true }]` to those files. The rule can't be disabled inline.
```typescript
// Bad - breaks on mobile
import * as fs from 'fs';
fs.readFileSync(path);
// Good - guarded for desktop only
import { Platform } from 'obsidian';
if (Platform.isDesktop) {
const fs = await import('fs');
fs.readFileSync(path);
}
```
Also counted as guarded: the `else` of `if (!Platform.isDesktop)`, the right side of `Platform.isDesktop && …` or `!Platform.isDesktop || …`, and code after an early exit such as `if (!Platform.isDesktop) return;` anywhere before the call (v0.5.1; it was first statement only). `Platform.isDesktopApp`, `!Platform.isMobile`, and `!Platform.isMobileApp` count as `Platform.isDesktop` (v0.5.1). Type-only imports (`import type { Stats } from 'fs'`) are not reported. v0.5.0 also reports `window.require('fs')`, `activeWindow.require('fs')`, `export … from 'fs'`, and `import fs = require('fs')`. v0.5.1 doesn't report a `require()` or awaited `import()` in a `try` with a `catch`, an optional call (`window.require?.('fs')`), or `.d.ts` files. Since v0.6.0, a `try` whose `catch` always rethrows is **not** a guard, an early exit in a `switch` case guards the rest of that case, and a bare `require?.('fs')` is reported — the bundle's own `require` exists on mobile too, so only `window.require?.('fs')` is safe:
```typescript
// Bad — bundle's require exists on mobile; throws for a Node.js module
const fs = require?.('fs');
// Good — only the desktop app puts require on the global object
const fs = window.require?.('fs') as typeof import('fs') | undefined;
```
### Restricted HTTP/util imports (use Obsidian built-ins)
**Rule:** `@typescript-eslint/no-restricted-imports` (configured by `recommended`)
The recommended config flags HTTP clients and `moment`, because Obsidian bundles equivalents:
```typescript
// Bad — use requestUrl() instead (axios, got, ky, node-fetch, ofetch, superagent)
import axios from 'axios';
// Good
import { requestUrl } from 'obsidian';
// moment is bundled with Obsidian — don't add it as a dependency
// Bad
import moment from 'moment';
// Good — the value comes from 'obsidian'
import { moment } from 'obsidian';
// Type-only imports from 'moment' ARE allowed (allowTypeImports):
import type { Moment } from 'moment';
```
The same rule warns on restricted globals: `app` (use your plugin's reference), `fetch` (use `requestUrl`), and `localStorage` (use `App#saveLocalStorage`/`loadLocalStorage`).
## Running the Lint
Run from the project root so `package.json`, `manifest.json`, and `LICENSE` are linted too:
```bash
# Good — lints source plus package.json, manifest.json, LICENSE
npx eslint .
# Bad — never visits manifest.json/LICENSE/package.json; their checks silently do nothing
npx eslint src/
```
Type-checked linting is slower than basic linting because it loads the TypeScript program. For a typical Obsidian plugin, expect 3-10 seconds.
## Checklist Before Submission
1. `npm run build` succeeds
2. `npx eslint .` (from the project root) shows zero errors and zero warnings
3. All tests pass
4. No unguarded Node.js modules: every `require()`/`import()` of a Node built-in sits behind `Platform.isDesktop` (unless `isDesktopOnly: true`) — check with `grep -rn "require(\|import(" src/`
5. No `console.log` or `console.info` calls
6. No unhandled promises (search for `MarkdownRenderer.render`, `clipboard.writeText`, `workspace.revealLeaf` without `void`/`await`)
7. No bare `document` usage (use `activeDocument` or `el.doc`); no `window` for DOM work (use `activeWindow`), except timers
8. No bare `setTimeout`/`setInterval` and no `activeWindow.setTimeout()` (use `window.setTimeout()` etc.)
9. Use `getLanguage()` instead of `localStorage.getItem('language')` for i18n
10. DOM listeners on `document`/`window`/long-lived elements use `registerDomEvent()` — the linter does not flag manual `addEventListener` (check with `grep -rn "addEventListener" src/`)
## Troubleshooting
### `WARNING: You are currently running a version of TypeScript which is not officially supported`
**Cause:** You have old `@typescript-eslint/parser` v7.x installed, which only supports TypeScript <5.6.0. TypeScript 5.9+ triggers this warning.
**Fix:** Migrate to the unified `typescript-eslint` v8.x package:
```bash
npm uninstall @typescript-eslint/eslint-plugin @typescript-eslint/parser eslint && \
npm install -D typescript@latest eslint typescript-eslint @typescript-eslint/parser eslint-plugin-obsidianmd
```
Then update your `eslint.config.mjs` to import the parser from `typescript-eslint`:
```js
import tseslint from "typescript-eslint";
// Use tseslint.parser or import @typescript-eslint/parser separately
```
### `ERESOLVE unable to resolve dependency tree`
**Cause:** npm refuses to install because of peer dependency conflicts. Usually means:
1. TypeScript version is too old (need >=4.8.4 for typescript-eslint 8.x)
2. Old @typescript-eslint packages are still in package.json
**Fix:** Uninstall old packages and upgrade TypeScript in one command:
```bash
npm uninstall @typescript-eslint/eslint-plugin @typescript-eslint/parser eslint && \
npm install -D typescript@latest eslint typescript-eslint @typescript-eslint/parser eslint-plugin-obsidianmd
```
### `TypeError: scopeManager.addGlobals is not a function`
**Cause:** Version conflict between old `@typescript-eslint/*` packages (v5-7) and new `typescript-eslint` (v8+).
**Fix:** Remove the old packages completely:
```bash
npm uninstall @typescript-eslint/eslint-plugin @typescript-eslint/parser
npm install -D typescript-eslint @typescript-eslint/parser
```
### `Parsing error: Unexpected character 'e' found` (or similar)
**Cause:** TypeScript files aren't being parsed as TypeScript. Usually means:
1. TypeScript version is too old (need 5.x+ for typescript-eslint 8.x)
2. Parser isn't configured correctly
3. Version conflicts between packages
**Fix:**
```bash
npm install -D typescript@latest
# Then reinstall eslint packages
npm uninstall eslint typescript-eslint @typescript-eslint/parser eslint-plugin-obsidianmd
npm install -D eslint typescript-eslint @typescript-eslint/parser eslint-plugin-obsidianmd
```
### `Error while loading rule: You have used a rule which requires type information`
**Cause:** `parserOptions` isn't set, or the file being linted isn't included in any `tsconfig.json`.
**Fix:** Use `projectService` with `allowDefaultProject` for files outside your tsconfig:
```js
languageOptions: {
parserOptions: {
projectService: {
allowDefaultProject: ["eslint.config.*"],
},
},
}
```
If using the older `project` approach instead, ensure your tsconfig.json includes your source files:
```json
{
"include": ["src/**/*.ts"]
}
```
### "… requires type information" on `LICENSE`, `manifest.json`, or `package.json`
**Cause:** A type-checked config added without `files` (e.g. a top-level `...tseslint.configs.strictTypeChecked`) reaches the files the recommended config lints by name. New in v0.5.0 for `manifest.json` and `LICENSE`.
**Fix:** Scope it with `files: ["**/*.ts"]` (see [Layering stricter typescript-eslint configs](#layering-stricter-typescript-eslint-configs)). If the unscoped config comes from somewhere you can't edit, add these blocks **last**:
```js
{
files: ["package.json", "manifest.json", "LICENSE", "LICENSE.md", "LICENSE.txt"],
extends: [tseslint.configs.disableTypeChecked],
},
{
files: ["**/*.ts"],
rules: { "@typescript-eslint/no-misused-promises": "off" },
},
```
### `could not find plugin "@typescript-eslint"` (or `"import"`)
**Cause:** A rule-override block without `files` sets a `@typescript-eslint/*` or `import/*` rule and reaches `package.json`/`manifest.json`/`LICENSE`, where those plugins aren't registered.
**Fix:** Add `files: ["**/*.{ts,cts,mts,tsx,js,cjs,mjs,jsx}"]` to the block (see [Scope overrides with `files`](#scope-overrides-with-files)).
### `Cannot redefine plugin "json"` or `Cannot redefine plugin "@typescript-eslint"`
**Cause:** Your config imports `@eslint/json` or `typescript-eslint` itself, and your project has a different copy from the one the plugin uses. Most often `@eslint/json` 0.x next to v0.5.0's 2.x, or Yarn 1 with an exact version pin.
**Fix:** Upgrade `@eslint/json` to 2.x (or remove it if your config doesn't import it). With Yarn 1, use a caret range (`"^8.59.1"`) or `resolutions`. `npm ls typescript-eslint @eslint/json` lists the copies.
### `Cannot read properties of undefined (reading 'includes')` with `--fix-dry-run`
**Cause:** `parserOptions.project` + TypeScript 6 in typescript-eslint's single-run mode. The recommended config turns single-run off under `--fix-dry-run`. If you fix via ESLint's API with `CI=true`, set `parserOptions.disallowAutomaticSingleRunInference: true`, or use `projectService` instead.
### npm `ERESOLVE overriding peer dependency` with ESLint 10
**Cause:** Three bundled plugins (`@microsoft/eslint-plugin-sdl`, `eslint-plugin-import`, `eslint-plugin-react`) don't declare ESLint 10 support yet. Linting works; ignore the warnings. With `strict-peer-deps` the install fails — turn the setting off or use ESLint 9.
### npm `deprecated eslint@9.39.5: This version is no longer supported`
**Cause:** npm marks ESLint 9 deprecated now that ESLint 10 is current. Linting works. Moving to ESLint 10 trades this one warning for the three `ERESOLVE` warnings above, so ESLint 9 is still the quieter choice until the bundled plugins declare ESLint 10 support.
### `npm audit`: moderate vulnerabilities in `minimatch` (GHSA-g3hv-75wg-m249)
**Cause:** `minimatch` before 11.0.1 has a denial-of-service advisory, and the toolchain doesn't ship a patched version yet: `typescript-eslint`'s `typescript-estree` depends on `minimatch ^10`, and `@microsoft/eslint-plugin-sdl` (bundled by `eslint-plugin-obsidianmd`) pins `eslint-plugin-n` 17.10.3, which uses `minimatch ^9`. One advisory shows up as about 10 findings along those chains. It is dev-time only — nothing reaches `main.js` — but the scanner's Review lists "No known vulnerable dependencies".
❌ **INCORRECT** — npm's suggested "fix" downgrades to `eslint-plugin-obsidianmd` 0.0.2 and `typescript-eslint` 8.36.0:
```bash
npm audit fix --force
```
✅ **CORRECT** — force the patched `minimatch` with a scoped override in `package.json`, then reinstall:
```json
{
"overrides": {
"minimatch@>=7 <11.0.1": "^11.0.5"
}
}
```
The range `>=7 <11.0.1` matches only the vulnerable versions, so ESLint 9's own `minimatch` 3.x is left alone. JSON has no comments; to explain the override in the project, add a top-level `"//"` key, which npm ignores (the `create-plugin` tool does this):
```json
{
"//": ["overrides.minimatch: temporary fix for GHSA-g3hv-75wg-m249; remove once upstream depends on minimatch 11."],
"overrides": {
"minimatch@>=7 <11.0.1": "^11.0.5"
}
}
```
For an existing project, add the override, then reinstall from scratch so the lockfile picks it up: `rm -rf node_modules package-lock.json && npm install`. Other package managers: pnpm uses `"pnpm": { "overrides": { "minimatch@>=7 <11.0.1": "^11.0.5" } }`; Yarn uses `"resolutions": { "minimatch": "^11.0.5" }`, which applies to every copy, including ESLint 9's `minimatch` 3.x — run `npx eslint .` afterwards to confirm it still works.
Verified with `eslint-plugin-obsidianmd` 0.6.0, `typescript-eslint` 8.72.2, and ESLint 9.39.5 (2026-11-14): `npm audit` reports 0 vulnerabilities, and type-aware rules and `allowDefaultProject` (the code in `typescript-estree` that uses `minimatch`) still work.
**When to remove it.** The override forces a major version past the range the toolchain declares, so delete it (and the `"//"` note) as soon as upstream no longer needs it. Check both chains:
```bash
npm view @typescript-eslint/typescript-estree dependencies.minimatch # needs ^11
npm view @microsoft/eslint-plugin-sdl dependencies.eslint-plugin-n # 17.10.3 pulls minimatch ^9
```
When `typescript-estree` asks for `^11` and `eslint-plugin-sdl` depends on an `eslint-plugin-n` that no longer uses `minimatch` 9/10 (or `eslint-plugin-obsidianmd` drops it), remove the override, reinstall from scratch, and confirm `npm audit` still reports 0. If a future `typescript-eslint` breaks with `minimatch` 11 before then (errors from `allowDefaultProject` or "was not found by the project service"), remove the override and accept the advisory until upstream ships a fix.
### `file not found in project` errors
**Cause:** The file being linted isn't included in your tsconfig.json's `include` pattern.
**Fix:** Update tsconfig.json to include all source files:
```json
{
"include": ["src/**/*.ts"]
}
```
### `… was included by allowDefaultProject but also was found in the project service`
**Cause:** A file matched by `allowDefaultProject` is also in a `tsconfig.json`. Usually `eslint.config.*` with a tsconfig whose `include` takes in root files (`["**/*.ts", "**/*.mts"]`, or `["**/*"]` with `allowJs`).
**Fix:** Do one or the other, not both — drop the pattern from `allowDefaultProject` (the tsconfig already gives the file type information), or leave the file out of the tsconfig's `include`. `allowDefaultProject` is for files in no tsconfig only.
### Package manager conflicts (pnpm/npm/yarn mixing)
**Cause:** Using pnpm on a project that was set up with npm (or vice versa) causes packages to be moved to `node_modules/.ignored`.
**Fix:** Stick to one package manager. To switch cleanly:
```bash
rm -rf node_modules package-lock.json pnpm-lock.yaml yarn.lock
# Then use your preferred package manager:
npm install # or pnpm install
```
### ESLint can't find the config file
**Cause:** Using `.eslintrc.*` (old format) instead of `eslint.config.mjs` (flat config).
**Fix:** ESLint 9+ uses flat config by default. Remove old config files and create `eslint.config.mjs`:
```bash
rm -f .eslintrc .eslintrc.js .eslintrc.json .eslintrc.yml
# Then create eslint.config.mjs with the config from this guide
```
### tsconfig.json shows errors in VSCode/VSCodium (TypeScript 5.9+)
**Cause:** TypeScript 5.9+ deprecated several tsconfig options:
- `moduleResolution: "node"` — deprecated, use `"bundler"` for esbuild projects or `"node10"` for tsc-only
- `baseUrl` — deprecated (removed in TS 7.0), remove if not using path aliases
**Fix:** Update tsconfig.json:
```json
{
"compilerOptions": {
"moduleResolution": "bundler"
// Remove "baseUrl" if you're not using path aliases
}
}
```
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| brainstormingobra/superpowersYou MUST use this before any creative work - creating features, building components, adding functionality, modifying behavior, or planning anything new, in software or out of it (a talk, a business, a renovation). | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| brand-guidelinesanthropics/skillsApplies Anthropic's official brand colors and typography to any sort of artifact that may benefit from having Anthropic's look-and-feel. Use it when brand colors or style guidelines, visual formatting, or company design standards apply. | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |
| frontend-designanthropics/skillsGuidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making choices that don't read as templated defaults. | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |
| mcp-builderanthropics/skillsGuide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when building MCP servers to integrate external APIs or services, whether in Python (FastMCP) or Node/TypeScript (MCP SDK). | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |