[英]How to set a base path for SCSS imports in SvelteKit?
我想在我的一個組件中導入一個 scss 文件。 有沒有辦法使用別名或其他東西,這樣我就可以在沒有很長的相對路徑的情況下導入它們。
例如,而不是這樣: <style lang='scss'> @use '../../../styles/main.scss' </style>
我想做這樣的事情: <style lang='scss'> @use '@/styles/main.scss' </style>
我正在使用 sass a svelte-preprocess 包。
這在 Vue 中有效,但不確定在 svelte 中是否可以做類似的事情。
好的,經過大量的谷歌搜索和試驗,我想我已經想出了一個解決方案。
首先,我改用vitePreprocess處理器而不是 svelte-preprocess。 根據說明,需要將svelte.config.js
編輯為如下所示:
import adapter from '@sveltejs/adapter-auto';
import { vitePreprocess } from '@sveltejs/kit/vite';
/** @type {import('@sveltejs/kit').Config} */
const config = {
kit: {
adapter: adapter()
},
preprocess: [vitePreprocess()] // Add this line and its import (above)
};
export default config;
然后在vite.config.js
中編輯如下:
import { sveltekit } from '@sveltejs/kit/vite'
import path from 'path'
/** @type {import('vite').UserConfig} */
const config = {
plugins: [
sveltekit()
],
resolve: {
alias: {
'@': path.resolve('src') // Styles in src/styles will be accessible as '@/styles/whatever.scss'
}
}
}
export default config
這實現了我的目標,盡管熱模塊重新加載不能正常工作。 對 scss 文件的更改不會觸發自動重新加載。 可能有幾個選項,但我喜歡以下選項,它使用vite-plugin-restart
模塊來監視樣式文件夾並在其中一個文件更改時重啟服務器。
第一的:
npm install --save-dev vite-plugin-restart
然后進一步編輯vite.config.js
看起來像這樣:
import { sveltekit } from '@sveltejs/kit/vite'
import VitePluginRestart from 'vite-plugin-restart'
import path from 'path'
// No idea why this is needed
// The default export of vite-plugin-restart looks to be the function but it doesn't work when imported
// Need to access the 'default' key from the imported object instead
const ViteRestart = VitePluginRestart.default
/** @type {import('vite').UserConfig} */
const config = {
plugins: [
sveltekit(),
ViteRestart({
restart: [
'src/styles/*.scss' // For some reason path.resolve doesn't seem to work here
]
})
],
resolve: {
alias: {
'@': path.resolve('src')
}
}
}
export default config
每當您編輯其中一個 scss 文件時,vite 服務器將重新啟動。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.