如何向 SvelteKit/Vite 应用添加版本号?

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)

urb*_*rb_ 9

这就是我设法让它发挥作用的方法:

  • 按照 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),
      }
    },
  },
  // ...
};

Run Code Online (Sandbox Code Playgroud)
  • 在任何 svelte 文件中使用该变量:
<h2>Version: {__APP_VERSION__}</h2>
Run Code Online (Sandbox Code Playgroud)

和你的例子很相似,希望对你有帮助!

编辑:请注意,配置在@sveltejs/kit@1.0.0-next.359之后更改:

对 @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

  • @DigitalNinja vite 配置对象文档的 [define 部分](https://vitejs.dev/config/#define) 中有一条注释,建议“...在 env.d 中添加...类型声明”。 ts 或 vite-env.d.ts 文件来获取类型检查和智能感知。” 例如`声明 const __APP_VERSION__: string` (4认同)
  • 嗯,由于某种原因这对我不起作用。但你确实给我指出了正确的方向,所以我将 `__APP_VERSION__` 分配给另一个组件局部变量,上面有 `// @ts-ignore` ,这就成功了 (3认同)
  • 使用变量时,将以下注释放在该行上方:&lt;!-- svelte-ignore Missing-declaration --&gt; (2认同)

Kle*_*ber 7

您还可以使用版本属性。

文件: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 版本的情况下更新应用程序,则可能会发生不一致(请检查文档


xpu*_*puu 5

(更新的答案)在我的文章中,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)