hef*_*use 8 javascript build svelte vite sveltekit
我正在尝试在我的 SvelteKit 应用程序中创建一个系统,它会在某个页面上向您显示有关当前应用程序版本的信息(最好是 Git 提交哈希和描述)。我尝试使用Vite 的定义功能在构建时执行此操作,但似乎不起作用。我如何添加这样的东西?
这是我尝试做的一个例子:
svelte.config.js 中的 Vite 配置
vite: () => ({
define: {
'__APP_VERSION__': JSON.stringify('testfornow')
}
})
Run Code Online (Sandbox Code Playgroud)
索引.svelte:
<script lang="ts">
const version: string = __APP_VERSION__;
</script>
<p>Current App version: {version}</p>
Run Code Online (Sandbox Code Playgroud)
这就是我设法让它发挥作用的方法:
// 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),
}
},
},
// ...
};
Run Code Online (Sandbox Code Playgroud)
<h2>Version: {__APP_VERSION__}</h2>
Run Code Online (Sandbox Code Playgroud)
和你的例子很相似,希望对你有帮助!
对 @sveltejs/kit@1.0.0-next.359 进行重大更改后,Vite 配置必须包含在其自己的文件中:
// 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),
}
// ...
};
Run Code Online (Sandbox Code Playgroud)
并且config.kit.vite
必须从文件中删除该道具svelte.config.js
。
您还可以使用版本属性。
文件:svelte.config.js
const config = {
...
kit: {
...
version: {
name: process.env.npm_package_version
}
}
}
Run Code Online (Sandbox Code Playgroud)
这样,您就可以将应用程序的版本与 package.json 文件联系起来。
并使用它:
import { version, dev } from '$app/environment';
...
console.log(`Client version: ${version}`);
Run Code Online (Sandbox Code Playgroud)
请记住,使用此解决方案,如果您在不更改 package.json 版本的情况下更新应用程序,则可能会发生不一致(请检查文档)。
(更新的答案)在我的文章中,vite.config.js
我使用 exec 从 Git 获取信息。然后我使用 Vite 配置选项定义来进行不断的替换。
import { exec } from 'child_process'
import { promisify } from 'util'
// Get current tag/commit and last commit date from git
const pexec = promisify(exec)
let [version, lastmod] = (
await Promise.allSettled([
pexec('git describe --tags || git rev-parse --short HEAD'),
pexec('git log -1 --format=%cd --date=format:"%Y-%m-%d %H:%M"'),
])
).map(v => JSON.stringify(v.value?.stdout.trim()))
/** @type {import('vite').UserConfig} */
const config = {
define: {
__VERSION__: version,
__LASTMOD__: lastmod,
},
...
Run Code Online (Sandbox Code Playgroud)
如果您使用 Typescript,则需要转到app.d.ts
// App version
declare const __VERSION__: string
// Date of last commit
declare const __LASTMOD__: string
Run Code Online (Sandbox Code Playgroud)
常量__VERSION__
和__LASTMOD__
现在可用于整个应用程序。唯一的缺点是,如果您直接在标记中使用它们,vite-plugin-svelte 会抱怨它们没有定义。
<script context="module" lang="ts">
const versionInfo = `Version ${__VERSION__}, ${__LASTMOD__}`
</script>
<div>{versionInfo}</div>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4235 次 |
最近记录: |