【问题标题】:Rollup : single html output汇总:单个 html 输出
【发布时间】:2020-11-27 06:17:25
【问题描述】:

我正在尝试将我的 Svelte 应用程序打包到单个 Html 文件输出中。 我已经设法通过基于该答案的配置获得所需的输出: Output Single HTML File from Svelte Project

使用“npm run dev”,第一次构建一切正常,但我在(实时重载)构建后遇到问题:bundle['bundle.css'] 未填写在我的 inlineSveltegenerateBundle 函数中。

我没有设法将rollup-plugin-css-only 更改为rollup-plugin-embed-css,这似乎有一个适合我需要的名称。

这是我的rollup.config.js

import svelte from 'rollup-plugin-svelte';
import livereload from 'rollup-plugin-livereload';
import css from 'rollup-plugin-css-only';
...

function inlineSvelte(templatePath, dest) {
  return {
    name: 'Svelte Inliner',
    generateBundle(opts, bundle) {
      const file = path.parse(opts.file).base;
      const jsCode = bundle[file].code;
      const cssCode = bundle['bundle.css'].source;
      const template = fs.readFileSync(templatePath, 'utf-8');
      bundle[file].code = template
        .replace('%%script%%', jsCode)
        .replace('%%style%%', cssCode);
    }
  }
}

export default {
  input: 'src/main.js',
  output: {
    format: 'es',
    file: outputDir + 'index.html',
    name: 'app'
  },
  plugins: [
    svelte({
        compilerOptions: {
            dev: !production
        }
    }),
    css({ output: 'bundle.css' }),
    resolve({
        browser: true,
        dedupe: ['svelte']
    }),
    commonjs(),
    !production && livereload(outputDir),
    inlineSvelte('./src/template.html')
  ],
  watch: {
    clearScreen: false
  }
};

【问题讨论】:

    标签: javascript html svelte rollup livereload


    【解决方案1】:

    当然可以将生成的 CSS 文件嵌入到您的 HTML 中,至少使用一些相当简单的自定义插件。

    但是,如果您的 Svelte 组件中只有 CSS,即您的代码中没有 import 'whatever.css',您可以依赖 Svelte 从编译的 JS 代码中注入 CSS 并完成它。

    这在性能方面损失了一点,因为这种注入的 CSS 永远不会被浏览器缓存,但它避免了与自定义构建步骤相关的额外复杂性/风险/耦合......而且这种性能通常不是在您希望将所有应用程序都放在一个 HTML 文件中的情况下非常重要。

    要启用此功能,请在 Svelte 插件上设置 emitCss: false

      plugins: [
        svelte({
          emitCss: false,
          ...
        }),
        ...
      ],
      ...
    

    在这种情况下,您不需要任何 CSS 汇总插件。

    【讨论】:

    • 谢谢!成功了 :) 仍然很好奇如何使用单独的 css 代码来完成...
    • @Paul:问题与 rollup-plugin-css-only 有关。更多详情请查看github repro
    猜你喜欢
    • 2019-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-10
    • 1970-01-01
    • 2021-08-04
    • 1970-01-01
    相关资源
    最近更新 更多