【发布时间】:2023-02-02 00:51:47
【问题描述】:
我有我目前正在使用的 Wordplate/Wordpress 网站。 Wordplate/Wordpress 自带 Vite。
现在我的问题是,我正试图让 Vite 在 Wordpress 中工作,就像 HMR 一样。
我真正想要的是,每次我更新我的index.scss时,该网站都会获得这些更新。
现在,我已经将默认值 vite.config.js 覆盖为此
import { defineConfig } from "vite";
require("dotenv").config();
export default defineConfig(() => ({
publicDir: "resources/static",
build: {
assetsDir: "",
emptyOutDir: true,
manifest: true,
outDir: `public/themes/${process.env.WP_DEFAULT_THEME}/assets`,
rollupOptions: {
input: `public/themes/${process.env.WP_DEFAULT_THEME}/resources/js/index.js`,
},
},
plugins: [
{
name: "php",
handleHotUpdate({ file, server }) {
if (file.endsWith(".php")) {
server.ws.send({ type: "full-reload", path: "*" });
}
},
},
],
}));
我的index.js
import "../css/index.css";
index.css 是我的 index.scss 的输出,我在其中编写我的 css 代码,然后将其输出到 index.css。 index.css 是我的子主题用来应用样式的文件。
这是我的子团队的 functions.php 加载我的 js 和我的 css
<?php
function my_theme_enqueue_styles()
{
wp_enqueue_style('parent-style', get_template_directory_uri() . '/style.css');
}
add_action('wp_enqueue_scripts', 'my_theme_enqueue_styles');
// Register scripts and styles.
add_action('wp_enqueue_scripts', function () {
$manifestPath = get_theme_file_path('assets/manifest.json');
if (
wp_get_environment_type() === 'local'
&& is_array(wp_remote_get('http://localhost:5173/')) // is Vite.js running
) {
wp_enqueue_script('vite', 'http://localhost:5173/@vite/client', [], null);
wp_enqueue_script('vite', 'http://localhost:5173/resources/js/index.js', [], null);
} elseif (file_exists($manifestPath)) {
$manifest = json_decode(file_get_contents($manifestPath), true);
wp_enqueue_script(
'vite',
get_theme_file_uri('assets/' . $manifest['resources/js/index.js']['file']),
[],
null
);
wp_enqueue_style(
'vite',
get_theme_file_uri('assets/' . $manifest['resources/css/index.css']['file']),
[],
null
);
}
});
// Load scripts as modules.
add_filter('script_loader_tag', function (string $tag, string $handle, string $src) {
if (in_array($handle, ['vite', 'vite'])) {
return '<script type="module" src="' . esc_url($src) . '" defer></script>';
}
return $tag;
}, 10, 3);
实际上,每次我在index.scss 中进行一些更改然后手动刷新浏览器时,我都可以看到更改。
但我不想手动做,我希望它是自动的。
请如果有人这样做,我需要你的帮助。谢谢。
【问题讨论】: