我正在尝试将css后台url中的所有图像路径替换为base64编码的字符串,同时进行汇总构建。
为此,我使用rollup-plugin-postcss,我能够在构建中生成一个单独的.css文件,但我希望图像路径被base64编码的数据URL所取代。
如下所示:
background: url('images/sample.png');至
background: url('data:image/png;base64,R0lGODlhyAAiALM...DfD0QAADs=');这是我一直在做的事情:
import postcss from 'rollup-plugin-postcss'
...
plugins: [
postcss({
extensions: ['.css'],
extract: path.resolve('dist/index.css'),
}),
]发布于 2021-10-06 09:21:14
一种可能的解决方案是使用postcss-url
import postcssurl from 'postcss-url';
postcss({
..., // postcss options
plugins: [
postcssurl({
url: 'inline',
}),
],
}),发布于 2021-09-29 09:45:33
我不确定是否可以使用rollup-plugin-postcss,尝试使用“image-to-base64”npm它非常简单,下载命令:
npm i -S镜像到base64
示例:
const imageToBase64 = require('image-to-base64');
//or
//import imageToBase64 from 'image-to-base64/browser';
imageToBase64("path/to/file.jpg") // Path to the image
.then(
(response) => {
console.log(response); // "cGF0aC90by9maWxlLmpwZw=="
}
)
.catch(
(error) => {
console.log(error); // Logs an error if there was one
}
)这里有更多的例子
如果你需要更多的帮助,你可以回复这个评论。
发布于 2021-10-03 09:54:41
下面是一个基于此rollup starter的工作示例
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import { terser } from 'rollup-plugin-terser';
import path from 'path'
import postcss from 'rollup-plugin-postcss'
import base64Inliner from 'postcss-inline-base64'
// `npm run build` -> `production` is true
// `npm run dev` -> `production` is false
const production = !process.env.ROLLUP_WATCH;
const __dirname = path.resolve();
const baseDir = path.join(__dirname, 'public')
export default {
input: 'src/main.js',
output: {
file: 'public/bundle.js',
format: 'iife', // immediately-invoked function expression — suitable for <script> tags
sourcemap: true
},
plugins: [
postcss({
extensions: ['.css'],
extract: path.resolve('public/styles.css'),
plugins: [base64Inliner({ baseDir })]
}),
...
]
};然后我在src文件夹中创建了一个css文件:
body {
background: url('b64---./images/test.png---');
}在index.js中:
import "./styles.css";在index.html中
....
<title>rollup-starter-app</title>
<link href="styles.css" rel="stylesheet" />
....我能够得到:

https://stackoverflow.com/questions/69334379
复制相似问题