我已经搜索并应用了各种方法,但仍无法通过Webpack和Vue成功编译.vue文件中寻址的图像资源。
我试图摆弄文件加载器,url-loader,不同的引用图像和左右导入的方式,即使它没有在下面的代码中显示。我想我应该要求得到一个确凿的教育答案。
请注意,从代码中删除图像后一切正常。
错误
ERROR in ./node_modules/vue-loader/lib/template-compiler?{"id":"data-v-8959d626","hasScoped":false,"optionsId":"0","buble":{"transforms":{}}}!./node_modules/vue-loader/lib/selector.js?type=template&index=0!./src/js/component.vue
Module not found: Error: Can't resolve './assets/img/test.jpg' in 'D:\Projects\Web\src\js'
@ ./node_modules/vue-loader/lib/template-compiler?{"id":"data-v-8959d626","hasScoped":false,"optionsId":"0","buble":{"transforms":{}}}!./node_modules/vue-loader/lib/selector.js?type=template&index=0!./src/js/component.vue 28:27-59
@ ./src/js/component.vue
@ ./src/js/main.js
@ multi (webpack)-dev-server/client?http://localhost:8080 ./src/js/main.js
webpack: Failed to compile.
component.vue
<template>
<div>
<img src="./assets/img/test.jpg">
</div>
</template>
main.js
import Vue from 'vue';
import VueRouter from 'vue-router';
import component from './component.vue';
Vue.config.devtools = true;
Vue.use(VueRouter);
const routes = [{
path: '/component',
component: component
}
];
const router = new VueRouter({
routes,
mode: 'history'
});
new Vue({
el: '#app',
router
});
webpack.config.js
var path = require('path');
module.exports = {
entry: './src/js/main.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'public/dist'),
publicPath: '/public/dist/'
},
module: {
rules: [{
test: /\.less$/,
use: ['style-loader', 'css-loader', 'less-loader']
},
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
// `vue-loader` options
}
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000
}
}
]
},
resolve: {
alias: {
'vue$': 'vue/dist/vue.esm.js'
}
}
};
文件结构
src
- assets
-- img
--- test.jpg
- js
-- component.vue
-- main.js
答案 0 :(得分:1)
路径必须是相对的。由于您位于js
文件夹,因此必须使用..
:
<img src="../assets/img/test.jpg">
它就像常规文件夹导航一样。由于<template>
位于src/js/component.vue
,要访问test.jpg
,您可以:
src/js/component.vue
src/js/
../
现在你在src/
../assets
现在你在src/assets
../assets/img
现在你在src/assets/img
../assets/imgtest.jpg
现在您获得了src/assets/img/test.jpg
正如@AkinHwan in the comments所指出的,资产行为的一个很好的资源/参考是 https://vuejs-templates.github.io/webpack/static.html