Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.1k views
in Technique[技术] by (71.8m points)

使用 Rollup 打包 Vue 组件,如何打包 style 标签中使用 url() 引入的图片?

现有 rollup.config.js

import vue from 'rollup-plugin-vue';
import babel from 'rollup-plugin-babel';
import { terser } from 'rollup-plugin-terser';
import css from 'rollup-plugin-css-only';
import commonjs from '@rollup/plugin-commonjs';
import resolve from 'rollup-plugin-node-resolve';
import url from '@rollup/plugin-url';
// import postcss from 'rollup-plugin-postcss'

const production = process.env.NODE_ENV === 'production';

export default {
  input: 'src/main.js',
  output: {
    file: 'dist/bundle.js',
    format: 'esm',
    name: 'App',
    sourcemap: true
  },
  plugins: [
    vue({
      css: false
    }),
    css({ output: 'bundle.css' }),
    url({
      destDir: `./dist/assets`
    }),
    resolve(),
    commonjs(),
    babel(),
    production && terser()
  ]
};

文件目录结构:

.
├─babel.config.js
├─package.json
├─rollup.config.js
├─yarn.lock
├─src
|  ├─App.vue
|  ├─img.jpg
|  └main.js

App.vue 中的代码

<template>
  <div class="background">
    <h1>{{ message }}</h1>
    <button class="button" @click="handleButtonClick">click me</button>
  </div>
</template>

<script>
import { defineComponent, ref, watch } from 'vue';

export default defineComponent({
  name: 'App',
  setup() {
    const message = ref('');
    const clicked = ref(false);

    const handleButtonClick = () => {
      clicked.value = !clicked.value;
    };

    watch([clicked], () => {
      if (clicked.value) {
        message.value = 'Hello World!';
      } else {
        message.value = 'Hello Vue!';
      }
    });

    return {
      message,
      clicked,
      handleButtonClick
    };
  }
});
</script>

<style>
.button {
  width: 60px;
  height: 30px;
  color: aqua;
  background: orange;
  border-color: transparent;
  outline-color: transparent;
  border-radius: 6px;
}

.background {
  background-image: url('./img.jpg');
}
</style>

.vue 文件的 style 标签中使用 url() 引入的图片最终不会被打包到 dist 目录下,但是如果在 js 代码中 import img from './img.jpg 图片就能打包进 dist/assets 目录。

请问有什么方式能够解决在 style 中使用 url() 引入静态资源的打包和路径转换问题?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

顶一下,别沉了


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...