如何更改<img>的src属性在带有 webpack 和 vue-loader 的 .vue 文件中? [英] How to change the src attribute of <img> in .vue files with webpack and vue-loader?
问题描述
我有一个使用 webpack(版本 3.6.0)和 vue-loader(版本 13.0.5)构建的 vue.js(版本 2.4.4)应用程序.
I have a vue.js (version 2.4.4) application built with webpack (version 3.6.0) and vue-loader (version 13.0.5).
在.vue文件中,我需要根据我应用的环境修改<img>
标签的src属性中包含的url.
In the .vue files, I need to modify the url contained in the src attribute of the <img>
tags according to the environment of my application.
- 在开发环境中,图片必须来自应用程序文件夹,相对路径:/src/images/exemple.png"
- 在生产环境中,镜像必须来自cdn,并且绝对路径:"https://my-cdn.net/images/exemple.png一个>"
在webpack.config.js"文件中,我已经使用process.env.NODE_ENV"区分了不同的环境,如下所示:
In the "webpack.config.js" file, I already differentiate the different environments using "process.env.NODE_ENV", like this:
const isDev = process.env.NODE_ENV === 'dev';
但我不知道如何使用 vue-loader(或其他东西)修改我的 .vue 文件中 img 标签的 src 属性.
But I don't know how to modify the src attribute of the img tags in my .vue files with vue-loader (or with something else).
有关信息,这里是webpack.config.js"文件中 vue-loader 的定义:
For information, here is the definition of the vue-loader in the "webpack.config.js" file:
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
'scss': [
'vue-style-loader',
'css-loader',
'sass-loader'
]
}
}
}
有没有简单的方法可以做到这一点?
Is there a simple way to do this?
推荐答案
@Michael Levy 的回答:
我目前在使用 Vue 3、@vue/cli 4.5.10 和 webpack 时遇到了这个问题.经过大量研究,我已经解决了.
I am currently having this issue with Vue 3, @vue/cli 4.5.10, and webpack. I've solved it after much research.
Webpack 配置进入vue.config.js
,这里有很多抽象.要微调控制,您可以使用 chain webpack 配置.为了帮助您,当您尝试通过链接访问特定加载器时,请使用 Vue Inspect
.
Webpack configurations go into vue.config.js
, where there is a lot of abstraction. To fine tune control, you can use chain webpack configs. To help you, use Vue Inspect
when you are trying to access specific loaders via chaining.
$ vue inspect > output.js
这会给你一个很好的列表,列出了 vue-cli 正在使用的所有加载器.
That will give you a nice list of all the loaders that vue-cli is using.
例如 - 要在 vue.config.js
中修改 webpack 图片选项,您可以使用 vue inspect >output.js
,搜索output.js
文件,发现管理图片的加载器.
For example - to modify webpack image options within vue.config.js
, you can use vue inspect > output.js
, search the output.js
file, and discover the loader that's managing images.
即:/* config.module.rule('images').use('url-loader') */
回答问题 - 在你的 vue.config.js
To answer the question - in your vue.config.js
module.exports = {
chainWebpack: (config) => {
config.module
.rule("images")
.use("url-loader")
.tap((options) => {
options.name = "images/[name].[ext]";
options.publicPath = isDev ? __webpack_public_path__ : 'https://my-cdn.net/';
return options;
});
},
};
这篇关于如何更改<img>的src属性在带有 webpack 和 vue-loader 的 .vue 文件中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!