首页 文章

vue webpack项目img无法加载静态src

提问于
浏览
5

在我的vue(2.0)webpack项目中,我配置了vue-html-loader,但在我的.vue文件中,img标签无法加载静态src图像 . 下面是我的webpack配置:

module: {
    loaders: [
        ...
        {
            test: /\.html$/,
            exclude: /node_modules/,
            loaders: ['html', 'html-minify']
        }
        , {
            test: /\.vue$/,
            loader: 'vue'
        }
        ...
    ]
},
vue: {
    ...
    html: {
        root: path.resolve(__dirname, './source/static'),
        attrs: ['img:src', 'img:srcset']
    },
    loaders: {
        css: ExtractTextPlugin.extract("css"),
        sass: ExtractTextPlugin.extract("css!sass")
    }
},
resolve: {
    root: [
        path.resolve('./source')
    ],
    extensions: ['', '.js', '.json', '.scss', '.html', '.css', '.vue'],
    alias: {
        'vue': 'vue/dist/vue.js'
    }
},

下面是我的.vue文件:

<img src="/web/img/sieleLogo@1x.png" srcset="/web/img/sieleLogo@2x.png" />

我的浏览器总是出现404错误 . 有人得到同样的问题吗?

2 回答

  • 0

    我在我的webpack配置中有以下内容,它对我有用:

    module: {
        rules: [
          {
            test: /\.vue$/,
            loader: 'vue',
            options: vueConfig
          },
          {
            test: /\.js$/,
            loader: 'babel',
            exclude: /node_modules/
          },
          {
            test: /\.(png|jpg|gif|svg)$/,
            loader: 'url',
            options: {
              limit: 10000,
              name: '[name].[ext]?[hash]'
            }
          }
        ]
      }
    

    我在 src/assets 文件夹中有图像,我可以访问和显示,没有任何特定设置 .

  • 0

    我会在你的webpack别名中为你的静态 img 目录添加一个别名,即

    resolve: {
      ...
      alias: {
        'vue': 'vue/dist/vue.js',
        'img': path.resolve(__dirname, '../web/img') // or wherever it is located relative to this file
      }
    }
    

    现在您可以通过 ~img 引用静态图像,即

    <img src="~img/sieleLogo@1x.png" srcset="~img/sieleLogo@2x.png" />
    

    为确保您可以在html中解析上述内容,您需要将 vue-html 加载程序添加到您的webpack配置中:

    module: {
      loaders: [
        ...
        {
            test: /\.html$/,
            loaders: 'vue-html'
        }
    

    我只想用上面的代码替换你当前的html加载器 .

    不过所有这一切 - 由于脚手架的复杂性,一个坚实的webpack vue应用程序,我强烈建议你安装 vue-clihttps://github.com/vuejs/vue-cli

    然后,您可以简单地推出经过测试和运行的webpack环境:

    https://github.com/vuejs-templates/webpack

    只需将您的应用程序复制到其中您可能需要进行一些重构,但设置的时间节省是绝对值得的 .

相关问题