astro 调用组件前的逻辑判断并不能阻击打包组件内的客户端 JS

41 天前
 wdssmq

想着用选项控制在开启时引放评论

---
import Waline from "@/theme-simple/components/Waline.astro";
import { config } from "@/theme-simple/config";
---
{
    console.log(config.waline.enable)
}
{
    config.waline.enable && <Waline />
}

选项关闭时,html 不会被引入,但是 JS 仍然会打包进来执行。结果就是因为 html 元素不存在而报错。。对应的打包体积也会增加。。

---
import { config } from "@/theme-simple/config";
const configWaline = config.waline;
---

<div id="waline"></div>

<script define:vars={{ configWaline }}>
    import { init } from "@waline/client";
    import "@waline/client/style";
    document.addEventListener("DOMContentLoaded", (event) => {
        init({
            el: "#waline",
            serverURL: configWaline.serverURL,
        });
    });
</script>

可以改成 <script is:inline define:vars={{ configWaline }}>,然而这样又不能从 npm 加载文件了,需要走 CDN 。。

就很纠结。。

771 次点击
所在节点    Node.js
2 条回复
epiloguess
41 天前
你可以先通过 getelementbyid 判断一下元素的存在,再附加事件。
如果是静态生成的话,这种做法就不会把 js 打包进来了
epiloguess
41 天前
@epiloguess 可能就不会

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/1041110

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX