October 6, 2022

Robotic Notes

All technology News

Use HTML files as Vue templates with Webpack

2 min read


August 31, 2022

By combining Vue and Webpack, you can use HTML files for your Vue templates. IN modules.rules[] property, you need to insert the following object into the array:

modules: 
  rules: [
    
      test: /\.html$/i,
      type: 'asset/source'
    
  ]

For example, below is a Webpack configuration we use for one of our projects.

'use strict';

const webpack = require('webpack');

module.exports = 
  mode: 'development',
  entry: 
    app: `$__dirname/src/index.js`
  ,
  target: 'web',
  optimization: 
    minimize: false
  ,
  output: 
    path: `$__dirname/dist`,
    filename: '[name].js'
  ,
  plugins: [
    
  ],
  module: 
    rules: [
      
        test: /\.html$/i,
        type: 'asset/source'
      ,
      
        test: /\.css$/i,
        type: 'asset/source'
      
    ]
  
;

On Webpack 5, setting the type to asset/source means that if you import or require() a .html file, you get back the contents of the file as a string. This works great for Vue’s template Property. In older versions of Webpack you would use raw-loader instead.

const template = require('./template.html');

const app = Vue.createApp();

app.component('my-component', 
  template: template
);

A node

You can also import HTML files as strings into Node.js for server-side rendering. Here’s how you can make Node’s require() function returns HTML files as strings.

const fs = require('fs');

require.extensions['.html'] = function(module, filename) 
  module.exports = fs.readFileSync(require.resolve(filename), 'utf8');
;

const template = require('./template.html');
typeof template; 

Vue School has some of our favorite Vue video courses. Their Vue.js Masterclass walks you through building a real-world app and does a great job of teaching you how to integrate Vue with Firebase. Look at this!


More Vue tutorials



Source link