yuanchuan / sveltekit-autoimport Goto Github PK
View Code? Open in Web Editor NEWAutomatically detect and import components/modules for SvelteKit projects
Home Page: https://npm.im/sveltekit-autoimport
License: MIT License
Automatically detect and import components/modules for SvelteKit projects
Home Page: https://npm.im/sveltekit-autoimport
License: MIT License
I have a SvelteKit site that uses MDsveX to convert Markdown files into Svelte components.
I have built a set of design components that I would like editors to use to extend the Markdown that they write.
I would like to free the editors from adding all of the import statements for every component that they want to use in their Markdown.
I found your plugin which would be perfect, but I am struggling to get it to work with my setup.
If I remove MDsveX and only use .svelte components directly, then this plugin works fine, but doesn't solve my issue.
Any help in configuring this plugin to auto-import for components in the .md files would be wonderful.
Please see this StackBlitz where I have setup a simple reproduction of the problem I am seeing on my site.
https://stackblitz.com/edit/sveltejs-kit-template-default-n8m4fc?file=vite.config.js
[plugin:vite-plugin-svelte] /src/routes/blockTest/+page.md:12:27 Expected }
/src/routes/blockTest/+page.md:12:27
10 |
11 |
12 | <p><Layout_MDSVEX_DEFAULT {…$$props} {…metadata}></p>
^
13 | <h2>Intro</h2>
14 | <p>Hello there!</p>
Hey,
The 'page' module out of all other $app/stores modules causes this error.
VM10:6772 crbug/1173575, non-JS module files deprecated.
autoImport({
module: {
'$app/stores': [
'page',
]
}
})
The other 'getStores','navigating' ,'session','updated', imports are working just fine as of 1.6.2
Thank you for your time and effort.
Great library, I hope it becomes a default part of the main Sveltekit one day, like its port library is for Nuxt 3 now.
First and foremost: great initiative! I'm loving this! (after seeing nuxt3's auto imports implementation)
The power of auto imports
in my eyes are how frictionless it is to just drop a new file in say ./src/lib/components/Counter.svelte
and just refer to it else where with <Counter />
without having to care for import and/or restarting dev server.
Would this be possible as an opt-in behaviour for .js
-files as well?
Nuxt3 has this in the form of composables
:
https://v3.nuxtjs.org/guide/directory-structure/composables
Proposal:
import autoImport from 'sveltekit-autoimport';
const config = {
kit: {
vite: {
plugins: [
autoImport({
components: ['./src/lib/components'],
modules: ['./src/lib/js']
}};
]
}
}
}
Notice the "s" in modules
(not module, which already exists for external packages).
The dream here would be to support both default export
s & named export
s.
Say I have:
./src/lib/js
utils.js
onePlusOne.js
./src/lib/js/utils.js
export const pad = () => // pad code
export const offset = () => // offset code
./src/lib/js/onePlusOne.js
export default () => 1 + 1;
And in ./src/lib/components/Counter.svelte
being able to do:
<script>
console.log(onePlusOne());
console.log(pad());
</script>
Interesting one here.
<script lang="ts">
import { fly } from 'svelte/transition'
</script>
<script lang="ts">
import { fly } from 'svelte/transition'
let y: number
</script>
Something about this let y: number
is breaking the import in this file. I don't have a reproduction yet, but I can make one.
Is there a way to automatically import { base } from "$app/paths"?
I can't figure out.
This package would be amazing if it could be combined with sveltekit-preprocess-markdown - to be able to abstractly mention shared components without the need to add a <script> tag in md files.
Unfortunately I wasn't able to set it up, Proabably due to the order in which preprocess-markdown and this package run, since this is a vite plugin, the other a sveltekit preprocess plugin.
When doing
$: console.log(page)
, it logs as {subscribe: ƒ}
but
$: console.log($page)
, throws an error; page is not defined
I can only assume this is due to the $
, and autoimport does not check for an auto-subscription pattern, when determining whether to make an import or not.
Is there a way to define values that should be checked for auto-subscriptions, such as this case:
module: {
'$app/stores': ['page', 'session']
},
@ v1.0.0-next.350
There's still missing the official docs about vite.config.js
. Will it be the single config file or both vite.config.js
and svelte.config.js
are required in the project?
preprocessor
, maybe it's now inside vite.config.js
.I think one would just expect it to work there as-well. In my case, I was doing
export const id = derived(page, $page => $page.url.searchParams.get('id'))
*The import doesn't have to be inside the modules script-tag.
So I guess it could be included the checking phase of the script tag?🤔
I'm trying to use sveltekit-autoimport
to auto import svelte/transition
module. Probably this is not an issue and just my wrong use or a setting that I'm missing.
Inside vite.config.js
import { defineConfig } from 'vite'
import { svelte } from '@sveltejs/vite-plugin-svelte'
import autoImport from 'sveltekit-autoimport'
export default defineConfig({
plugins: [
autoImport({
components: ['./src/components'],
module: {
svelte: ['onMount', 'createEventDispatcher'],
'svelte/transition': ['fly'],
'svelte-apollo': ['mutation']
},
}),
svelte()
]
})
Everything is working fine, except: 'svelte/transition': ['fly']
I also tried using different combinations and mapping instead of module but couldn't make it work. The same happens with Vaadin web components.
I absolutely love not having to constantly manage my imports (very Swift-like), but - sadly - working with this plugin results in a somewhat cumbersome workflow due to the lack of IDE support. In particular: while it's possible to suppress Svelte's compiler warnings and VSCode's built-in auto importing features, you end up without any component IntelliSense due to the latter.
Has anyone managed to create a nice workflow for themselves despite this? I'd love to hear about your setup.
Ah yes, two in a row. Sorry😬
As an example, consider
import Button as _Button from `./Button.svelte`
import Continue from `./buttons/Continue.svelte`
import Back from `./buttons/Back.svelte`
const Button = _Button
Button.Continue = Continue
Button.Back = Back
export default Button
Then all of these would be valid
<Button>
<Button.Continue>
<Button.Back>
The config to the above is
modules: {
'$components/ui/button': ['default as Button']
}
// Works fine
<Button>
<Button.Continue>
// Throws error: `ReferenceError: Button is not defined`
<Button.Continue>
I acknowledge not many does component indention — but I have seen it before.
Still working on a reproduction of this one, but I found an interesting issue.
Using a auto imported <Button>
I found that a line in my css causes the build to fail.
.search-button {
margin-top: 0.5rem;
padding-right: 1rem;
}
So straight up deleting that search button css would fix this issue.
Hi @yuanchuan . First off, Nice one for svelte projects. I wish to know how nested components in the components folders are handled by this. Are they namespaced into the component name like unplugin-vue-components ?
What's the best way to use components that I have installed into the project through NPM package.json?
Reproduction: https://github.com/stolinski/auto-import-lib-bug
1 | <script
2 | import FormButton from '../components/form/button.svelte'
^
3 | lang="ts">
4 | </script>
If you are using typescript, your IDE is going to complain about missing declarations of auto-imported components. Unlike the svelte-error missing-declaration
, it isn't really feasible to turn these warnings off, as you would loose too many other important warnings.
You can get Typescript to find a Component, even if it is not imported, by adding a Declaration inside an ambient type-definition file.
declare const MyComponentTag1: typeof import('./path/to/MyComponent1.svelte')['default']
declare const MyComponentTag2: typeof import('./path/to/MyComponent2.svelte')['default']
MyComponentTag1
and MyComponentTag2
would now be resolved.
This plugin could auto-generate these type-definitions, whenever it resolves an auto-import, and place them in an ambient declaration file (maybe inside the hidden .svelte-kit
folder where the other auto-generated types are). Typescript would then be able to find these Components.
These type defitions are global, and are therefore available inside all typescript files, not just svelte files. I have been using this method manually for a while, and this hasn't really been an issue, just something to be aware of.
These definitions do not override explicitly imported Components.
I would be willing to implement this, if you are interested.
I have a fairly blank starter theme running on sveltekit latest which uses sveltekit plugin for vite and a vite.config file.
my vite.config.js file looks like
import { sveltekit } from '@sveltejs/kit/vite';
import autoImport from 'sveltekit-autoimport';
/** @type {import('vite').UserConfig} */
const config = {
plugins: [
sveltekit(),
autoImport({
components: [{ name: 'src/components/skeleton' } ],
})
]
};
export default config;
the src/components/skeleton has one file at src/components/skeleton/Menu.svelte for testing with this markup
<h1>This is a menu component</h1>
error message
Error: Failed to parse source for import analysis because the content contains invalid JS syntax. If you are using JSX, make sure to name the file with the .jsx or .tsx extension.
at formatError (/Users/whart/www/koios/node_modules/vite/dist/node/chunks/dep-80fe9c6b.js:39055:46)
at TransformContext.error (/Users/whart/www/koios/node_modules/vite/dist/node/chunks/dep-80fe9c6b.js:39051:19)
at TransformContext.transform (/Users/whart/www/koios/node_modules/vite/dist/node/chunks/dep-80fe9c6b.js:58269:22)
at async TransformContext.plugin.transform (file:///Users/whart/www/koios/node_modules/vite-plugin-inspect/dist/index.mjs:164:25)
at async Object.transform (/Users/whart/www/koios/node_modules/vite/dist/node/chunks/dep-80fe9c6b.js:39292:30)
at async doTransform (/Users/whart/www/koios/node_modules/vite/dist/node/chunks/dep-80fe9c6b.js:50012:29)
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.