Search code examples
htmlvue.jswebpackvuejs2vue-cli

Vue import HTML from local file


I am looking for a way to import HTML content from a file which is in

/src/activities/0/2/content.html

The two numbers are variables.

I need to do something like

mounted(){
   this.foo = require('/src/activities/0/2/content.html')
}
<div>
{{ foo }}
</div>

But I do not find a way to do this. If someone knows a solution, it will be very helpful.

Thank you


Solution

  • First Vue's webpack needs to understand how to load .html files. You can use html-loader. Install it first:

    npm install html-loader --save-dev
    

    Then edit (or create) vue.config.js in the project root (not src). From the docs:

    module.exports = {
      chainWebpack: config => {
        config.module
          .rule('html')
          .test(/\.html$/)
          .use('html-loader')
          .loader('html-loader')
      }
    };
    

    Now you can import HTML files like:

    import html from '@/activities/0/2/content.html'
    
    export default {
      data() {
        return {
          html,   // es6 property shorthand syntax
          foo: null
        }
      }
    }
    

    and use html like any other data variable. Or you can do it the way you asked with require:

    mounted(){
       this.foo = require('@/activities/0/2/content.html')
    }
    

    @ is an alias for src