femundfilou/kirby-vite

在 Kirby 中使用 Vite 前端工具。

安装次数: 2,010

依赖者: 0

建议者: 0

安全: 0

星标: 1

关注者: 1

分支: 0

开放问题: 1

类型:kirby 插件

0.1.1 2023-10-05 10:30 UTC

This package is auto-updated.

Last update: 2024-09-05 12:24:49 UTC


README

这是一个用于使用由 Vite 生成的脚本的 Kirby CMS 插件。

原因

这个插件是根据个人需求使用 Vite 作为前端工具而构建的。尽管已经有一些针对相同用例的优秀插件,但在使用 svelte 组件时,我遇到了一些问题。我的构建输出由来自不同 svelte 组件的多个 JavaScript 和样式表文件组成。虽然 JavaScript 导入被内部处理,但 CSS 条目不会被渲染。这就是为什么这个插件内置了一个方法来为所有来自 Vite 的非入口样式表生成链接标签。

其他流行的插件

还有一些其他用于相同用例的插件,您可以看看它们。

安装

composer require femundfilou/kirby-vite

设置

此插件附带两个辅助函数来渲染您的资产。

<!DOCTYPE html>
<html>
  <head>
    <?php
    /**
     * In production, this will generate a link tag with the main options entry. In development, it will return nothing.
     * */
    echo vite()->css();

    /**
     * Optionally: You can use different templates per page to split up css. This will generate the link tag for the given template.
     * */
    $template = $page->template();
    $entry = "frontend/templates/$template/index.ts";
    echo vite()->css($entry);
    /**
     * Optionally: Adding null as argument will render all css files from manifest.json that are not marked as [ 'isEntry' => true ]
     * */
    echo vite()->css(null);
    ?>
  </head>
  <body>
  <main>...</main>
  <?php
    /**
     * In production, this will generate a script tag with the main options entry. In development, it will create two script tags, one for vite client server and one for the main entry.
     * */
    echo vite()->js();

    /**
     * Optionally: You can use different templates per page to split up js.
     * This will generate the script tag for the given template.
     * */
    $template = $page->template();
    $entry = "frontend/templates/$template/index.ts";
    echo vite()->js($entry);
    ?>
  </body>
</html>

选项 + 默认值

此插件旨在与 laravel valet 一起使用,这是一个非常不错的本地开发工具,因此默认服务器地址。当然,您可以更改它,但必须与您的 vite.config.js 中的设置相同。

如果您使用 valet,您可以将代理添加到典型的 localhost:3000,以获取带有 SSL 的通用 Vite 域名,如下所示 valet proxy vite https://:3000 --secure

默认配置

您可以在您的 site/config.php 中覆盖此配置。

return [
  'femundfilou.vite' => [
    'main' => "frontend/index.ts", // Main vite entry
    'manifest' => 'manifest.json', // Path to manifest, relative from root
    'server' => 'https://vite.test:3000', // Server used in development
    'dev' => false // Toggle development on / off
  ]
];

自动切换开发与生产

我推荐的方式是通过使用 .env 变量自动从 development 切换到 production

  1. 安装 vlucas/phpdotenv
composer require vlucas/phpdotenv
  1. 在根目录创建 .env 文件

  2. index.php 中加载 .env

use Dotenv\Dotenv;
$dotenv = Dotenv::createImmutable(__DIR__);
$dotenv->load();
  1. site/config.php 中使用它
return [
  'femundfilou.vite' => [
    'dev' => $_ENV["MODE"] === "dev"
  ]
];
  1. 现在您需要一种更新 .env 文件的方法,例如通过 pipeline 或在运行 npm 时,具体取决于您的系统,例如这样
{
  "scripts": {
    "dev": "sed -i '' -e 's/production/dev/g' path/to/.env && vite",
    "build": "sed -i '' -e 's/dev/production/g' path/to/.env && vite build"
  }
}

旧模式

目前此插件仅生成 type="module" 脚本,因此不支持 Vite 旧模式。