How to reference image paths with specific prefixes in UNI-app for example:
background-image: url('@images/aaa.png');
Copy the code
This is… How come you haven’t seen it before
I received a small demand these days. My colleague’s project is Uni-app. The problem he encountered was that he could not use the custom prefix to process the image path in the code
// no
resolve: {
alias: {
'@images': path.resolve(__dirname, '.. /src'),}},// yes
resolve: {
alias: {
'@images': 'http://www.xxx.com',}},Copy the code
The colleague said he tried to write it like this, en… “I didn’t try again because it would seem disrespectful (after all, we were right next to each other and he could see everything I was doing with his glasses)
He told me the solution he came up with, which was to use CSS variables in CSS and JS variables in JS, and I said, ok, that’s a possible solution, but…
My colleague disliked this method and asked me if I could use a similar way of writing custom variables to answer: Yes! I’ll get this for you later.
Custom loader?
I suddenly thought of a way to intercept the source code and do a process before webPack compiled. Can be specific implementation logic: a custom loader, accept the source code and process, return the source code, to vue-loader to continue the original processing logic
On the whole
1. Modify the vue.config.js configuration file to add customized loader processing content before vue-loader
// Do not use configureWebPack, it will react with vue-CLI logic
chainWebpack: (config) = > {
config.module
.rule('vue')
.use('vue-loader')
.end()
.use('customLoader')
.loader(path.resolve(__dirname, './customLoader.js'))
.end();
}
Copy the code
2. Create customLoader.js and replace all image path prefixes of the specified format in the vue file with regular matches
module.exports = function(source) {
return source.replace(/@images\//g.'https://www.xxx.com/');
};
Copy the code
If you use a project not created by vuE-CLI, download the two plug-ins vue-loader vue-template-Compiler manually
Scatter flowers over…
My colleagues were just stunned. Is that it? .