离线/oc-vite-plugin

该包最新版本(v2.0.12)没有可用的许可证信息。

Vite集成于October CMS

安装: 320

依赖项: 0

建议者: 0

安全: 0

星标: 23

关注者: 5

分支: 8

开放问题: 0

类型:october-plugin

v2.0.12 2024-03-05 07:07 UTC

This package is auto-updated.

Last update: 2024-09-05 08:23:30 UTC


README

此插件提供了简单的Vite集成,适用于October CMS(版本3+)。

设置

使用composer安装插件

composer require offline/oc-vite-plugin

要使Vite集成正常工作,您首先需要将VITE_MANIFEST环境变量设置为Vite生成的清单文件路径。

# /themes/your-theme/assets/build/.vite/manifest.json
VITE_MANIFEST=assets/build/.vite/manifest.json

然后请确保将{% styles %}{% scripts %}标签放置在您的布局中,以便正确包含资源。

配置Vite

在您的主题中通过npm安装Vite。

npm install --dev vite@latest
# or
yarn add -D vite@latest

您可以修改以下Vite配置以打包您的主题资源

// themes/your-theme/vite.config.ts
import { defineConfig } from 'vite'
import { resolve, basename } from 'path'

// Your JS/TS/CSS entrypoints.
const input = {
    main: resolve(__dirname, 'resources/ts/main.ts'),
    css: resolve(__dirname, 'resources/scss/main.scss'),
}

// Auto detect the theme name, works only if one theme is available.
// const themeName = __dirname.match(/themes\/([^\/]+)/)[1];
const themeName = 'your-theme'

export default defineConfig({
    // Included assets will use this path as the base URL.
    base: `/themes/${themeName}/assets/build/`,
    build: {
        rollupOptions: { input },
        manifest: true,
        emptyOutDir: true,
        // Output assets to /themes/your-theme/assets/build
        outDir: resolve(__dirname, 'assets/build'),
    },
    server: {
        hmr: {
            // Do not use encrypted connections for the HMR websocket.
            protocol: 'ws',
        },
    }
})

工作流程

  • 要在开发中使用Vite,请使用vite命令启动Vite服务器
  • 要为生产构建资源,请使用vite build命令

包含Vite资源

您可以在Twig中的任何位置使用vite()函数来包含来自Vite开发服务器或Vite manifest.json(取决于环境)的资源。

您必须提供要包含的文件数组作为第一个参数。所有路径相对于主题目录。

{# includes /themes/your-theme/resources/ts/main.ts #}
{{ vite([ 'resources/ts/main.ts' ]) }}

{# or using the object syntax: #}
{{ vite([ { path: 'resources/ts/main.ts' }, { path: 'resources/scss/main.scss' } ]) }}

{# force a script/link tag if the asset has no extension:  #}
{{ vite([ { path: '@some-special-vendor-asset', ext: 'js' }, { path: '@has-no-extension', ext: 'css' } ]) }}

默认情况下,vite()函数将直接输出所需的资源到您的标记中。

使用October的资产管道

如果您想将资源推送到October的资产管道,可以将render参数设置为false。在这种情况下,将不会在vite()函数被调用的地方生成输出。

{{ vite([ { path: 'resources/ts/main.ts', render: false } ]) }}

请记住,为了使其正常工作,需要在您的布局中放置{% styles %}{% scripts %}标签。

传递额外属性

任何额外的属性都将传递到生成的HTML标签。

{{ vite([ { path: 'resources/ts/main.ts', defer: true ]) }}

从PHP代码中包含资源

您可以使用特殊的vite:标记在PHP中包含文件

$this->controller->addJs('vite:resources/ts/main.ts');

现在将使用October的资产管道包含该资源,并在您放置了{% scripts %}{% styles %}标签的地方输出。

环境

开发

默认情况下,localdev被视为开发环境。如果您的应用程序环境是开发环境,Vite开发服务器将自动为您包含。

您可以使用以下.env变量来配置如何包含Vite开发服务器

# These are the defaults:
VITE_MANIFEST_FILENAME=manifest.json
VITE_DEV_ENVS=dev,local
VITE_HOST=https://:5173

生产

如果您的应用程序配置为在生产环境中运行,则插件将自动使用Vite清单包含资源。