webpack 的別名好處大家也都了解, 但是 vue 的模板中, 對圖片地址使用別名時總出現問題, 很久時間的時間都沒找到解決辦法, 一度認為是 webpack 的原因...
alias: { 'src': path.resolve(__dirname, '../src'), 'assets': path.resolve(__dirname, '../src/assets'), 'components': path.resolve(__dirname, '../src/components')}<template> <img src="assets/images/logo.jpg" /></template><script>import 'assets/css/style.css'</script><style>.logo { background: url(asset/images/bg.jpg)}</style>上面的代碼, 你會發現只有引入style.css是成功的, 圖片地址和背景圖片地址都會解析失敗...
經過各種搜索找原因(這時候, 你會發現百度搜索這些技術型的內容, 真是垃圾中的戰斗機), 最終還是找到原因了...
vue-html-loader and css-loader translates non-root URLs to relative paths. In order to treat it like a module path, prefix it with ~
就是要在別名前面加一個~
最終代碼寫成:
alias: { 'src': path.resolve(__dirname, '../src'), 'assets': path.resolve(__dirname, '../src/assets'), 'components': path.resolve(__dirname, '../src/components')}<template> <img src="~assets/images/logo.jpg" /></template><script>import 'assets/css/style.css'</script><style>.logo { background: url(~asset/images/bg.jpg)}</style>意思就是: 告訴加載器它是一個模塊,而不是相對路徑
注意: 只有在template中的靜態文件地址和style中的靜態文件地址需要加~, 在script里的, 別名定義成什么就寫什么.
到此, 糾結了幾個月時間的問題, 終于解決了...
順便貼下自己使用的別名列表:
alias: {  'assets': path.resolve(__dirname, '../src/assets'),  'src': path.resolve(__dirname, '../src'),  '~api': path.resolve(__dirname, '../src/api'),  '~components': path.resolve(__dirname, '../src/components'),  '~pages': path.resolve(__dirname, '../src/pages'),  '~router': path.resolve(__dirname, '../src/router'),  '~store': path.resolve(__dirname, '../src/store'),  '~utils': path.resolve(__dirname, '../src/utils')}以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答