【问题标题】:Reference to static assets with vue + webpack in electron app在电子应用中使用 vue + webpack 引用静态资产
【发布时间】:2017-07-08 14:25:33
【问题描述】:

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

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

我的项目结构如下:

/my-project
  /app
    /components
      componentA.vue
      ...
    App.vue
    main.js
  /dist
  /assets
    logo.png
  package.json
  webpack.config.js
  ...

我的 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',
    }
  }
}

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

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

<script>
   ...
</script>

但是我有以下错误

Failed to load resource: net::ERR_FILE_NOT_FOUND file:///logo.png

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

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

【问题讨论】:

    标签: webpack vue.js webpack-2 webpack-file-loader


    【解决方案1】:

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

    <template>
        <div>
            <img class="ui small image" :src="imageSource">
        </div>
    </template>
    
    <script>
        export default {
            data(){
                return {
                    imageSource: require('../../assets/logo.png')
                }
            }
    </script>
    

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

    【讨论】:

    • 必须有更简单的方法,不是吗?例如,如果我有一个包含 25 个图像的静态站点,这意味着 25 个变量和需要语句。
    • @StephenTetreault 是的,这可以直接在模板中完成:src="require('@/assets/logo.png')"
    【解决方案2】:

    另一种方法是将图像存储在static 目录中。这样,您可以直接在 html 指令中添加图像路径。

    <template>
        <div>
            <img src="/static/example.png">
        </div>
    </template>
    
    <script>
        export default {}
    </script>
    

    【讨论】:

      猜你喜欢
      • 2020-10-01
      • 2018-10-08
      • 2019-09-21
      • 2019-05-23
      • 2017-09-16
      • 2016-07-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多