vue打包图片,图片地址不存在或者出现[object module],或者图片地址存在排查方式
vue 编译图片
vue编译图片loader有两种file-loader、url-loader。url-loader将图片编译为base64,file-loader编译为地址访问的图片,通常两种混用,通过limit控制base64与文件打包。
vue.config.js
chainWebpack(config) {
config.module.rule("images").use("url-loader").loader("url-loader").tap(options => {
return {
...options,
limit: 4096,
};
}).end();
}
webpack.config.js
module: {
rules: [{
test: /\.(svg|gif|png|jpe?g)(\?\S*)?$/,
loader: 'url-loader',
options: {
limit: 4096,
},
}]
}
require() 与require().default图片区别
我们可以将一张图片通过loader编译为一个js文件,nodejs使用require引入一个js导出的信息,而require().default 就是获取default属性或者默认导出信息。
当使用require().default或者requre()引入图片不生效时,那就是使用的方式与打包导出方式没有对应上。
通常遇到的情况是上面这种情况 [object Module], 这表示找到的是一个对象,这是发现使用require().default就能找到图片,但是我们通常希望不加default。需要配置esmodule
// vue.config.js
chainWebpack(config) {
config.module.rule("images").use("url-loader").loader("url-loader").tap(options => {
return {
...options,
limit: 4096,
fallback: {
loader: "file-loader",
options: {
name: "static/img/[name].[ext]",
// 是否模块化
esModule: false,
},
},
// 是否模块化
esModule: false,
};
}).end();
}
// webpack.config.js
module: {
rules: [{
test: /\.(svg|gif|png|jpe?g)(\?\S*)?$/,
loader: 'url-loader',
options: {
fallback: {
loader: 'file-loader',
options: {
name: path.posix.join(`img`, '[name].[ext]'),
// 是否模块化
esModule: false,
},
// 是否模块化
esModule: false,
},
limit: 4096,
},
}]
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/732cadd3907146ca91498cf119d11eec.png
出现以上问题检查图片编译 esModule的值,若为false,将require()的default属性去掉。
综上所述,如果使用require().default, 就不需要加esModule属性,或者esModule:true;若使用require()需要配置esModule:false。 (file-loader 4.2.0以上)