【问题标题】:Modify build path of assets in Vite/Rollup?修改 Vite/Rollup 中资产的构建路径?
【发布时间】:2022-06-25 08:40:37
【问题描述】:

假设我有这个文件夹结构:

parent
|-parent.html
|-parent.js
|-child
|--child.html
|--child.js

我希望它们在我的 dist 文件夹中以相同的结构输出。 默认情况下,这是得到的输出:

dist/assets/parent.js
dist/assets/child.js

我希望他们像这样输出:

dist/parent/parent.js
dist/parent/child/child.js

我尝试更改 Rollup 的 assetFileNames 选项,但它没有做任何事情。

【问题讨论】:

    标签: javascript rollup vite


    【解决方案1】:

    输出文件名在汇总中配置为build.rollupOptions。设置output.entryFileNames 配置入口.js 文件的位置以匹配其原始目录结构:

    // vite.config.js
    import { fileURLToPath } from 'url';
    import { defineConfig } from 'vite';
    import path from 'path';
    
    const rootDir = fileURLToPath(new URL('.', import.meta.url));
    
    export default defineConfig({
      build: {
        rollupOptions: {
          input: {
            parent: './parent/parent.html',
            child: './parent/child/child.html',
          },
          output: {
            entryFileNames: (assetInfo) => {
              // assetInfo.facadeModuleId contains the file's full path
              if (assetInfo.facadeModuleId) {
                const assetPath = path.dirname(assetInfo.facadeModuleId).replace(rootDir, '');
                return assetPath + '/[name]-[hash].js';
    
              } else {
                return 'assets/js/[name]-[hash].js';
              }
            },
          },
        },
      },
    });
    

    demo

    注意事项

    • 资产(例如.css 文件)和共享模块(供应商.js 块)无法使用上述解决方案重定向,因为来自相关挂钩的资产信息不提供文件的完整路径。

    • 在一个普通的 Rollup 项目中,output.preserveModules=true 会完成最初的目标,但该选项与 Vite 自己的 Rollup 设置冲突。

    【讨论】:

      猜你喜欢
      • 2023-01-02
      • 2022-06-10
      • 1970-01-01
      • 2022-07-12
      • 2022-07-16
      • 2021-10-18
      • 2013-06-30
      • 2021-06-09
      • 2021-12-13
      相关资源
      最近更新 更多