feat: Add svelte/valid-context-access
rule
This is came from sveltejs/svelte#7864
According to the docs, getContext
needs to call during component initialization.
Svelte team tried to implement this in the compiler, but this is a bit difficult, so I thought that we will implement this as ESLint rule.
https://svelte.dev/docs#run-time-svelte-getcontext
Retrieves the context that belongs to the closest parent component with the specified key. Must be called during component initialisation.
<script>
import { getContext } from 'svelte';
let test = getContext('test');
</script>
<!-- β GOOD -->
<a href={test}>xxx</a>
<!-- β BAD -->
<a href={getContext('test')}>xxx</a>
No response
close: #448
Latest commit: ffc0bce
The changes in this PR will be included in the next version bump.
Name | Type |
---|---|
eslint-plugin-svelte | Minor |
Not sure what this means? Click here to learn what changesets are.
Click here if you're a maintainer who wants to add another changeset to this PR
I realized that itβs impossible to check async/await things perfectly. For example below case, it will be an error but I think it isn't easy to detect it by ESLint.
So my opinion is that we will mention this limitation on the docs and we don't check async/await things. Or we don't implement this rule. There may not be much value in the rule that includes this false negative. What do you think @ota-meshi ?
<script>
import { setContext } from "svelte"
import someAsyncProcess from './outside'
someAsyncProcess(() => {
setContext("answer", 42)
});
// outside.js
export async function someAsyncProcess(fn) {
await Promise.resolve();
fn();
}
Hmm. You're right, there are false negatives, but I don't think users will use setContext that way, so I don't think it matters much if it's not reported.
I think code like the following is a common mistake, so I think there's value in having it reported by a rule.
const something = async () => {
await Promise.resolve()
setContext("answer", 42)
}
eslint-plugin-vue has some similar checking rules. https://eslint.vuejs.org/rules/no-expose-after-await.html https://eslint.vuejs.org/rules/no-lifecycle-after-await.html https://eslint.vuejs.org/rules/no-watch-after-await.html https://eslint.vuejs.org/rules/no-restricted-call-after-await.html
The repository has been migrated to a monorepo. I'm marking this as a draft because I think it requires major changes. If anyone wants to implement this, feel free to open another PR.
Merge remote-tracking branch 'upstream/main' into feat/448