使用vue cli .
出于某种原因,我的一些图像,如果我直接在scss中引用它们并且不将它们动态地绑定到我的vue对象,则会产生相对路径问题 .
假设我有一个名为box的div的vue模板 . Box有一个背景网址:
.box {background:url('../ img / box.jpg')
当我运行npm run dev时,本地工作就好了 . 但是当我运行构建时,它不起作用 . 404错误 . 我也试过这样做:
.box{
background: url('~../img/box.jpg')
那没用 .
所以这就是:
webpack css-loader not finding images within url() reference in an external stylesheet
当我在webpack.config中更改它时:
output: {
path: path.resolve(__dirname, './dist'),
publicPath: '/dist/',
filename: 'build.js'
},
至:
output: {
path: path.resolve(__dirname, './dist'),
publicPath: './dist/',
filename: 'build.js'
},
它将在我的webpack构建中创建Chunk Images,并使用哈希进行缓存 . 并且仅适用于未绑定在vue对象中的特定图像 .
然后我必须将这些图像拖到根目录文件夹....而不是我想要做的是将它们保存在相对于html文件的img文件夹中(简单地说是html文件):
<html lang="en">
<head>
<meta charset="utf-8">
<title>vue</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
<app></app>
<script src="dist/build.js"></script>
</body>
</html>
问题是,我是否必须从数据中绑定每个vue img ...或者如果我知道它不会被更改,我就不能直接引用图像 .
或者我的sass loader / webpack中有一些我不知道的设置 .
这是我的webpack配置:
var path = require('path')
var webpack = require('webpack')
module.exports = {
entry: './src/main.js',
output: {
path: path.resolve(__dirname, './dist'),
publicPath: './dist/',
filename: 'build.js'
},
resolveLoader: {
root: path.join(__dirname, 'node_modules'),
},
vue: {
html: {
root: path.resolve(__dirname, './dist')
}
},
module: {
loaders: [
{
test: /\.vue$/,
loader: 'vue'
},
{
test: /\.js$/,
loader: 'babel',
exclude: /node_modules/
},
{
test: /\.json$/,
loader: 'json'
},
{
test: /\.html$/,
loader: 'vue-html'
},
{
test: /\.scss$/,
loaders: ["style", "css", "sass"]
},
{
test: /\.(png|jpg|gif|svg)$/,
loader: 'url',
query: {
limit: 10000,
name: '[name].[ext]?[hash]'
}
}
]
},
devServer: {
historyApiFallback: true,
noInfo: true
},
devtool: '#eval-source-map'
}
if (process.env.NODE_ENV === 'production') {
module.exports.devtool = '#source-map'
// http://vue-loader.vuejs.org/en/workflow/production.html
module.exports.plugins = (module.exports.plugins || []).concat([
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"'
}
}),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
}),
new webpack.optimize.OccurenceOrderPlugin()
])
}
2 回答
我设法通过以下步骤复制您的问题:
假设以下目录:
和home.vue:
构建应用程序并将文件保存在
dist
文件夹后,如果我在dist
文件夹中使用此命令提供构建文件,则一切正常(为简单起见,我使用lite-server):但是,如果我回到根文件夹并尝试执行相同的操作:
我会遇到和你一样的问题 .
我通常如何解决这个问题,首先导入图像,然后使用内联样式:
另请参阅以下讨论:
Github: background image best practice
Github: html image src require not respecting webpack aliases?
Github: vue-loader not processing images in dynamic component
Github: problem with background url
StackOverflow: Vue.js data-bind style backgroundImage not working
StackOverflow: webpack css-loader not finding images within url() reference in an external stylesheet
取决于您的根设置,您可以尝试
background: url('~/assets/img/box.jpg')
或background: url('~/src/assets/img/box.jpg')
,其中一个应该工作