V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
wdssmq
V2EX  ›  Node.js

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

  •  
  •   wdssmq · 13 天前 · 531 次点击

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

    ---
    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 。。

    就很纠结。。

    2 条回复    2024-05-16 07:56:25 +08:00
    epiloguess
        1
    epiloguess  
       13 天前
    你可以先通过 getelementbyid 判断一下元素的存在,再附加事件。
    如果是静态生成的话,这种做法就不会把 js 打包进来了
    epiloguess
        2
    epiloguess  
       13 天前
    @epiloguess 可能就不会
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   3019 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 11:35 · PVG 19:35 · LAX 04:35 · JFK 07:35
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.