我正在尝试在我的 SvelteKit 应用程序中创建一个系统,它会在某个页面上向您显示有关当前应用程序版本的信息(最好是 Git 提交哈希和描述)。我尝试使用Vite的定义功能 https://vitejs.dev/config/#define在构建时执行此操作,但它似乎不起作用。我如何添加这样的东西?
这是我尝试做的一个例子:
svelte.config.js 中的 Vite 配置
vite: () => ({
define: {
'__APP_VERSION__': JSON.stringify('testfornow')
}
})
索引.svelte:
<script lang="ts">
const version: string = __APP_VERSION__;
</script>
<p>Current App version: {version}</p>
这就是我设法让它发挥作用的方法:
- 按照 SvelteKit FAQ 中的说明获取 package.json 数据,并将其作为常量加载到 Vite 配置中:
// svelte.config.js
import { readFileSync } from 'fs';
import { fileURLToPath } from 'url';
const file = fileURLToPath(new URL('package.json', import.meta.url));
const json = readFileSync(file, 'utf8');
const pkg = JSON.parse(json);
const config = {
kit: {
// ...
vite: {
define: {
'__APP_VERSION__': JSON.stringify(pkg.version),
}
},
},
// ...
};
<h2>Version: {__APP_VERSION__}</h2>
和你的例子很相似,希望对你有帮助!
编辑:请注意,配置更改后@sveltejs/[电子邮件受保护] https://github.com/sveltejs/kit/releases/tag/%40sveltejs%2Fkit%401.0.0-next.359:
对 @sveltejs/k 进行重大更改后[电子邮件受保护] /cdn-cgi/l/email-protection, Vite config 必须包含在自己的文件中:
// vite.config.js
import { readFileSync } from 'fs';
import { fileURLToPath } from 'url';
const file = fileURLToPath(new URL('package.json', import.meta.url));
const json = readFileSync(file, 'utf8');
const pkg = JSON.parse(json);
const config = {
define: {
'__APP_VERSION__': JSON.stringify(pkg.version),
}
// ...
};
And the config.kit.vite
支柱必须从svelte.config.js
file.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)