在电子应用程序中使用vue + webpack引用静态资产

Bik*_*mat 1 webpack vue.js webpack-2 webpack-file-loader

我是vuejs + webpack + electron的新手,我正在用这些工具开始一个新项目.

我很难在我的标签中检索资产的路径.

我的项目结构如下:

/my-project
  /app
    /components
      componentA.vue
      ...
    App.vue
    main.js
  /dist
  /assets
    logo.png
  package.json
  webpack.config.js
  ...
Run Code Online (Sandbox Code Playgroud)

我的webpack.config.js看起来像:

module.exports = {
  // This is the "main" file which should include all other modules
  entry: './app/main.js',
  // Where should the compiled file go?
  output: {
    // To the `dist` folder
    path: './dist',
    // With the filename `build.js` so it's dist/build.js
    filename: 'build.js'
  },
  module: {
    loaders: [
      {
        test: /\.vue$/,
        loader: 'vue-loader'
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        query: {
          presets: ['es2015']
        },
        exclude: /node_modules/
      },
      {
        test: /\.(jpeg|png|gif|svg)$/,
        loader: "file-loader?name=[name].[ext]"
      }
    ]
  },
  resolve: {
    alias: {
      'vue$': 'vue/dist/vue.common.js',
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

在文件componentA.vue中,我尝试执行以下操作:

<template>
    <div>
        <img class="ui small image" src="../../assets/logo.png">
    </div>
</template>

<script>
   ...
</script>
Run Code Online (Sandbox Code Playgroud)

但是我有以下错误

Failed to load resource: net::ERR_FILE_NOT_FOUND file:///logo.png
Run Code Online (Sandbox Code Playgroud)

浏览器试图加载file:///logo.png(这是错误的,因为它不是我的资产的完整路径,它错过了我的项目目录的整个路径)所以我试图把我的资产放在输出/ dist没有结果的文件夹(但我不确定我是否正确完成).

你能帮我解决这个问题吗?非常感谢 !

小智 6

为了使Webpack返回正确的路径,您需要进行以下更改:

<template>
    <div>
        <img class="ui small image" :src="imageSource">
    </div>
</template>

<script>
    export default {
        data(){
            return {
                imageSource: require('../../assets/logo.png')
            }
        }
</script>
Run Code Online (Sandbox Code Playgroud)

参考:https://github.com/vuejs-templates/webpack/issues/126

  • 一定有更简单的方法,不是吗?例如,如果我有一个包含 25 个图像的静态站点,则意味着有 25 个变量和 require 语句。 (2认同)