webpackwebpack-file-loaderwebpack-html-loader

webpack: alias does not work in HTML tags


Is there any reasons why the alias below does not work in HTML tags or work in JavaScript?

In my webpack config file:

  resolve: {
    alias: {
      '~': path.resolve(__dirname, './src/')
    }
  },
 ...
 ...
 ...

 {
    test: /\.(png|svg|jpg|gif|ico)$/,
    use: [
      {
        loader: 'file-loader',
        options: {
          outputPath: 'images',
          esModule: false,
          name: '../assets/images/[name].[ext]'
        },
      },
    ]
 },
 {
   test: /\.(html)$/,
   use: ['html-loader']
 }

In my HTML file (.vue):

// .vue
// Does not work
<template>
  <p><img src="~/assets/images/sample.jpg"></p>
</template>

// Ok
<script>
import Image from '~/assets/images/sample.jpg'
</script>

Am I missing something in my webpack configuration?


Solution

  • vue-html-loader and css-loader are actually used in this case.

    You can try this:

    <img class="logo" src="~assets/images/sample.jpg">
    

    or

    <template>
      <div>
        <img :src="sample" />
      </div>
    </template>
    
    <script>
    import image from '~/assets/images/sample.jpg';
    
    export default {
        data() {
            sample: image;
        }
    }
    </script>