typescript - 在 LitElement 项目中使用 @rollup/plugin-image 输出 svgs 以与 RollupJS 捆绑

标签 typescript svg web-component rollup lit-element

我正在使用 @rollup/plugin-image 来帮助解决我的 LitElement 项目中的 svg 导入问题,如下所示:https://github.com/rollup/plugins 。由于我使用的是 typescript,所以我还在 custom.d.ts 中声明了 '*.svg' 模块。

问题是我不知道如何在汇总的捆绑输出中包含 SVG 文件,这意味着我的浏览器稍后无法导入这些文件,并且我在控制台中看到 401 错误。为了暂时解决这个问题,我只在需要在自定义 LitElement 组件的 render() 函数中显示 SVG 的地方使用内联 SVG 标签。请帮助我了解我所缺少的内容。

我当前的(简化的)rollup.config.js:

// other imports ... 
import image from '@rollup/plugin-image';
const extensions = ['.js', '.ts'];
const commonPlugins = [
  json(),
  commonJS(),
  resolve({ module: true, jsnext: true, extensions }),
  postcss(),
  terser({ keep_classnames: true, keep_fnames: true }),
  **image(),** 
];
const babelPlugins = [
   ...
];
const babelInclude = [
   ...
];
const es6Bundle = {
  input: ['src/bundle/index.es6.ts'],
  output: {
    dir: 'dist/bundle',
    entryFileNames: 'index.js',
    format: 'iife',
    sourcemap: true,
  },
  plugins: [
    babel({
      extensions,
      presets: [
        [
          '@babel/preset-env',
          {
            targets: '>25%',
          },
        ],
        '@babel/typescript',
      ],
      plugins: babelPlugins,
      include: babelInclude,
    }),
    ...commonPlugins, // where image() gets included
  ],
};

export default [es6Bundle];

我的输出目录如下所示: dist/bundle/wc/*一堆 web-component.js 文件* dist/bundle 内部有index.js 和index.js.map。

我可能会在这里混淆不同的概念,如果是这样,我深表歉意。这是我第一次使用 rollup 和 litelement。

最佳答案

The issue is I don't know how to include SVG files in rollup's bundle output, which means my browser can't import those files later on and I see 401 errors in the console

@rollup/plugin-image的目标是让您在代码中内联图像,而不是在运行时导入它们,因此浏览器甚至不应该尝试加载它们......

应该这样使用:

import {html, LitElement, customElement} from 'lit-element';
import myImage from './image.svg';

@customElement('my-test')
export class MyTest extends LitElement {

  render() {
    return html`
      <img src="${myImage}">
      // Or like this, if the `dom` option
      // of the plugin is set to true:
      ${myImage}
    `;
  }

}

但是,我不建议将 SVG 内联为 base64:与其他图像格式不同,它完全可以与 HTML 互操作,那么为什么要增加其大小呢?请参阅here有关此主题的更多信息。

您可能想看看其他插件,例如 rollup-plugin-svg 让您可以将 SVG 捆绑为标记。

关于typescript - 在 LitElement 项目中使用 @rollup/plugin-image 输出 svgs 以与 RollupJS 捆绑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59401193/

相关文章:

javascript - 如何在 JavaScript 中使用 Promise

javascript - 增加 SVG 圆的大小

javascript - 如何向 SVG 图表添加线条(由 Google Visualization 绘制)

javascript - 清理自定义元素中的事件监听器

javascript - 已弃用的 Webpack 的 i18n 插件和加载器的替代品

typescript - Angular 2 : can't resolve global service

Angular 6 在 AngularElements 中使用 ContentChildren/ViewChildren - CustomComponents

javascript - noUIslider 在 web component-polymer 3(litelement) 中不起作用

javascript - 如何使 TypeScript 输出有效的 ES6 模块导入语句?

javascript - raphael.js 如何将 id 添加到路径