Vue.js项目引入图片报错:Module parse failed,需配置对应loader
Vue.js图片加载报错解决办法
你的问题根源在于webpack配置完全不对:你配置的是
.styl样式文件的loader,但报错的是图片文件;而且绝对不能修改node_modules里的配置——这会被依赖包更新覆盖,正确做法是在项目根目录创建vue.config.js来自定义配置。先确认安装
file-loader(Vue CLI 3+默认内置,但手动安装一遍确保没问题):
npm install file-loader --save-dev
- 在项目根目录新建
vue.config.js,添加图片文件的loader配置:
module.exports = { configureWebpack: { module: { rules: [ { test: /\.(png|jpe?g|gif|webp)$/i, use: [ { loader: 'file-loader', options: { name: '[name].[hash:8].[ext]', outputPath: 'assets/images' // 打包后图片输出的目录 } } ] } ] } } }
- 也可以用Vue CLI推荐的
chainWebpack写法,更灵活:
module.exports = { chainWebpack: config => { config.module .rule('images') .test(/\.(png|jpe?g|gif|webp)$/i) .use('file-loader') .loader('file-loader') .options({ name: '[name].[hash:8].[ext]', outputPath: 'assets/images' }) .end() } }
另外检查图片引用:
require('@/assets/blue.PNG')写法没问题,但要确保图片确实在src/assets目录下,文件名大小写要匹配(部分系统区分大小写,.PNG和.png会被识别为不同文件)。最后重启开发服务器,让新配置生效。
内容的提问来源于stack exchange,提问作者Wojciech
相关产品推荐
相关产品推荐

