Wednesday, September 18, 2024
HomeJavaScriptUse HTML Information as Vue Templates with Webpack

Use HTML Information as Vue Templates with Webpack


Aug 31, 2022

By combining Vue and Webpack, you should use HTML recordsdata in your Vue templates.
Within the modules.guidelines[] property, you have to insert the next object into the array:

modules: {
  guidelines: [
    {
      test: /.html$/i,
      type: 'asset/source'
    }
  ]
}

For instance, under is a Webpack config we use for considered one of our tasks.

'use strict';

const webpack = require('webpack');

module.exports = {
  mode: 'growth',
  entry: {
    app: `${__dirname}/src/index.js`
  },
  goal: 'net',
  optimization: {
    reduce: false
  },
  output: {
    path: `${__dirname}/dist`,
    filename: '[name].js'
  },
  plugins: [
    
  ],
  module: {
    guidelines: [
      {
        test: /.html$/i,
        type: 'asset/source'
      },
      {
        test: /.css$/i,
        type: 'asset/source'
      }
    ]
  }
};

On Webpack 5, setting the sort to asset/supply signifies that, when you import or require() a .html file, you get again the contents of the file as a string.
This works nice for Vue’s template property.
On older variations of Webpack, you’d use raw-loader as an alternative.

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

const app = Vue.createApp();

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

Node

You may as well import HTML recordsdata as strings in Node.js for server aspect rendering.
Here is how one can make Node’s require() perform return HTML recordsdata as strings.

const fs = require('fs');

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

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


Vue Faculty has a few of our favourite Vue
video programs. Their Vue.js Grasp Class walks you thru constructing an actual
world software, and does a terrific job of educating you how you can combine Vue
with Firebase.
Test it out!


Extra Vue Tutorials

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments