【问题标题】:How to add included Pug files to Vite module graph如何将包含的 Pug 文件添加到 Vite 模块图中
【发布时间】:2021-08-31 10:35:47
【问题描述】:

我编写了一个汇总插件来将 Pug 作为 HTML 字符串导入:

// Rollup plugin imported to Vite config

import { render } from 'pug';

export default function pug() {
  return {
    name: 'rollup-plugin-pug-html',

    transform(src, id) {
      if (id.endsWith('.pug')) {
        const html = render(src, { filename: id });
        const code = `export default ${JSON.stringify(html)};`;

        return { code };
      }
    },
  };
}

我在 Vite 中使用它来为 Vue 组件创建模板,如下面的简化示例:

// ProofOfConceptSFC.vue

<script>
import { compile } from 'vue/dist/vue.esm-bundler.js';
import template from './template.pug';

export default {
  render: compile(template)
};
</script>

当我编辑 template.pug 时,HMR 运行良好。新模板出现并且最新的反应值保持不变。

我的问题是template.pug 可能依赖于其他带有include 的 Pug 文件:

//- template.pug

include ./header.pug
p Hello {{ name }}
include ./footer.pug

Vite 服务器不知道这些文件,如果我触摸它们,什么也不会发生。理想情况下,当任何 Pug 文件更改时,我可以使 template.pug 无效。

我猜我希望我的插件更新 ViteDevServer 的server.moduleGraph。有支持的方法吗?

【问题讨论】:

    标签: vue.js pug vite


    【解决方案1】:

    非常感谢友好的Vite chat on Discord 为我指明了正确的方向。

    我丢失的两个键:

    1. 使用 Pug compile 创建具有 render.dependenciesas done by Parcelrender 方法
    2. 使用虚拟导入语句将依赖项附加到转换挂钩结果as done by vite-plugin-svelte

    这是工作插件:

    import { compile } from 'pug';
    
    export default function pluginPug() {
      return {
        name: 'vite-plugin-pug',
    
        transform(src, id) {
          if (id.endsWith('.pug')) {
            const render = compile(src, { filename: id });
            const html = render();
            let code = '';
    
            for (let dep of render.dependencies) {
              code += `import ${JSON.stringify(dep)};\n`;
            }
    
            code += `export default ${JSON.stringify(html)};`;
    
            return { code };
          }
        },
      };
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-04
      • 2020-09-08
      • 2020-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-02
      相关资源
      最近更新 更多