По требованию компоненты автоматический импорт для Svelte.
Sveltekit demo Svelte Vite Demo
pnpm add -D unplugin-svelte-components // vite.config.ts
import Components from 'unplugin-svelte-components/vite'
export default defineConfig ( {
plugins : [
Components ( { /* options */ } ) ,
] ,
} ) // rollup.config.js
import Components from 'unplugin-svelte-components/rollup'
export default {
plugins : [
Components ( { /* options */ } ) ,
] ,
} // webpack.config.js
module . exports = {
/* ... */
plugins : [
require ( 'unplugin-svelte-components/webpack' ) ( { /* options */ } ) ,
] ,
} // esbuild.config.js
import { build } from 'esbuild'
build ( {
/* ... */
plugins : [
require ( 'unplugin-svelte-components/esbuild' ) ( {
/* options */
} ) ,
] ,
} ) // vite.config.ts
import Components from 'unplugin-svelte-components/vite'
export default defineConfig ( {
plugins : [
Components ( { /* options */ } ) , // before sveltekit plugin
sveltekit ( ) ,
] ,
} ) Используйте компоненты, как вы обычно делаете, он будет импортировать компоненты по требованию, и им больше не требуется import !
Это автоматически перевернет это
< HelloWorld msg =" Hello Svelte " />в это
< HelloWorld msg =" Hello Svelte " />
< script >
import HelloWorld from './src/components/HelloWorld.svelte'
</ script > Чтобы получить поддержку TypeScript для автоматических компонентов, вы можете изменить конфигурацию как следующее, чтобы получить поддержку.
Components ( {
dts : true , // enabled by default if `typescript` is installed
} ) После того, как настройка будет выполнена, будут сгенерированы components.d.ts . Не стесняйтесь совершать это в GIT или нет, как вы хотите.
Убедитесь,
includesвы также добавляетеcomponents.d.tstsconfig.json
Круто, чтобы ваши собственные компоненты импортировали его, но иногда вы хотите импортировать сторонние компоненты.
Таким образом, unplugin-svelte-components предоставили способ импортировать эти компоненты.
Components ( {
dts : true ,
external : [
{
from : "agnostic-svelte" , // import from third party
names : [ // import these components
"Alert" ,
"Button as AButton" , // import as `AButton`
] ,
defaultImport : false , // telling `unplugin-svelte-components` to import any component as non-default export
} ,
] ,
} ) Таким образом, Alert и AButton будут доступны для использования.
В некоторых случаях вы можете отключить автоматический импорт на своей странице, unplugin-svelte-components предоставляет способ сделать это, просто добавив <!-- unplugin-svelte-components disabled --> в вашем файле .svelte
<!-- unplugin-svelte-components disabled -->
< HelloWorld msg =" Hello Svelte " /> Следующее показывает значения по умолчанию конфигурации
Components ( {
// relative paths to the directory to search for components.
dirs : [ 'src/components' ] ,
// valid file extensions for components.
extensions : [ 'svelte' ] ,
// search for subdirectories
deep : true ,
// generate `components.d.ts` global declarations,
// also accepts a path for custom filename
// default: `true` if package typescript is installed
dts : false ,
// Allow subdirectories as namespace prefix for components.
directoryAsNamespace : false ,
// Subdirectory paths for ignoring namespace prefixes
// works when `directoryAsNamespace: true`
globalNamespaces : [ ] ,
// Transform path before resolving
importPathTransform : v => v ,
// Allow for components to override other components with the same name
allowOverrides : false ,
// Accept a svelte pre-processor (e.g. svelte-preprocess)
preprocess : null ,
// filters for transforming targets
include : [ / .svelte$ / , / .svelte?svelte / ] ,
exclude : [ / [\/]node_modules[\/] / , / [\/].git[\/] / , / [\/].svelte-kit[\/] / , ] ,
// Generate corresponding .eslintrc-components.json file.
// eslint globals Docs - https://eslint.org/docs/user-guide/configuring/language-options#specifying-globals
eslintrc : {
enabled : true , // Default `true`
filepath : './.eslintrc-components.json' , // Default `./.eslintrc-components.json`
globalsPropValue : true , // Default `true`, (true | false | 'readonly' | 'readable' | 'writable' | 'writeable')
}
} ) Благодаря Энтони Фу, этот проект сильно вдохновлен неплугин-вуэкомпонентами.
Лицензия MIT © 2022-Present Mohamed Nesredin