如何在Vue汇总库中使用公共图像

时间:2019-07-10 10:30:02

标签: javascript vue.js rollupjs

我正在使用vue和汇总建立一个ui组件库,除了使用公共/静态图像时,其他所有组件都工作正常。

rollup.config.js

import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import vue from 'rollup-plugin-vue';
import sass from 'rollup-plugin-sass';
import replace from 'rollup-plugin-replace';
import { uglify } from 'rollup-plugin-uglify';

import pkg from './package.json';

const plugins = [
  vue(),
  replace({
    'process.env.NODE_ENV': JSON.stringify('production'),
  }),
  sass({
    insert: true,
  }),
  resolve(),
  commonjs(),
  uglify(),
];

export default [
  {
    input: 'src/main.js',
    output: {
      name: 'daas-components',
      file: pkg.browser,
      format: 'umd',
    },
    plugins,
  },
  {
    input: 'src/main.js',
    output: [
      { file: pkg.main, format: 'cjs' },
      { file: pkg.module, format: 'es' },
    ],
    plugins,
  },
];

/*
 Some component with images
 Now I'm using normal public path images use
*/

<template>
  <div class="Chip" :class="className" :data-cy="dataCy">
    <slot></slot>
    <div class="Chip__Actions">
      <div class="Chip__Actions__Closer" @click="onClose" v-if="isClosable">
        <img src="/icons/close.svg" alt="closer-chip" />
      </div>
      <div class="Chip__Actions__Addabler" @click="onAdd" v-if="isAddable">
        <img src="/icons/add.svg" alt="addabler-chip" />
      </div>
    </div>
  </div>
</template>


[...]

在主项目中使用库时,使用的图像带有'http :: // localhost:8080 / CURRENT_PATH / MY_IMAGE_PATH'前缀,因此它将在库项目中存储的图像中查找应用程序项目中存储的图像。

1 个答案:

答案 0 :(得分:0)

使用插件:@rollup/plugin-url来配置公共路径

// rollup.config.js

import url from 'rollup-plugin-url'

export default {
  // ...
  plugins: [
    // ...
    url({
      // by default, rollup-plugin-url will not handle font files
      include: ['**/*.svg', '**/*.png', '**/*.jpg', '**/*.gif', '**/*.woff', '**/*.woff2'],
      // setting infinite limit will ensure that the files 
      // are always bundled with the code, not copied to /dist
      limit: Infinity,
      publicPath: '/public',
    }),
  ],
  // ...
}