一、概述
項目目錄結構
./
├── assets
│ └── logo.png
└── components
└── test.vue
test.vue中的css樣式,需要引用assets下的logo.png文件。
#main {
width: 200px;
height: 200px;
background: url('logo.png');
}
運行后報錯:
ERROR Failed to compile with 1 errors 15:43:10
This relative module was not found:
* ./logo.png in ./node_modules/css-loader?{"sourceMap":true}!...
二、解決辦法
使用相對路徑
#main {
width: 200px;
height: 200px;
background: url('../assets/logo.png');
}
注意:用多少個../ 取決於vue文件和assets目錄之間,跨越了多少層級。
我這里只用了一個,如果你的層級比較深,需要添加多個../
完整代碼如下:
test.vue

<template> <div id="main"></div> </template> <script> export default { name: "test" } </script> <style scoped> #main { width: 200px; height: 200px; background: url('../assets/logo.png'); } </style>
訪問頁面,效果如下: