Conor  Grady

Conor Grady

1656734400

Vite Plugin Handlebars : Process HTML Files with Handlebars

vite-plugin-handlebars

Vite support for Handlebars

Why?

I really like Vite as a simple static site bundler. It can handle bundling multiple HTML files, which is great, but lacks the ability out-of-the-box to share parts of those HTML files.

While a JS framework like React or Vue could be used to solve this problem, this is heavy-handed for a simple site that could be completely pre-rendered without a JS run-time of any kind.

Handlebars provides what we need to be able to stitch together multiple HTML files, interpolate variables, etc.

Installation

Start by installing the package like you would any other

yarn add -D vite-plugin-handlebars

It can then be added to your Vite configuration as a plugin:

// vite.config.js
import handlebars from 'vite-plugin-handlebars';

export default {
  plugins: [handlebars()],
};

Configuring the plugin is covered later in this guide.

Requirements

  • This plugin is intended to work with Vite 2
  • This plugin requires Node 14 or higher (due to usage of fs/promises)

Configuration

Defining Context

If you want to make use of Handlebars Context to inject variables into your HTML file, you'll need to define their values in the context object passed to the handlebars plugin:

<!-- index.html -->
<h1>{{title}}</h1>
// vite.config.js
import handlebars from 'vite-plugin-handlebars';

export default {
  plugins: [
    handlebars({
      context: {
        title: 'Hello, world!',
      },
    }),
  ],
};

This will result in <h1>Hello, world!</h1> in your output HTML file.

You can also provide a (asynchronous) function, either as the context key or any of the keys within the object, which will be evaluated to create the value that will be made available inside your page. This function is called with an identifier parameter based on the HTML file path which makes it possible to provide unique data to each HTML page in a multipage application setup.

// vite.config.js
import handlebars from 'vite-plugin-handlebars';

const pageData = {
  '/index.html': {
    title: 'Main Page',
  },
  '/nested/subpage.html': {
    title: 'Sub Page',
  },
};

export default {
  plugins: [
    handlebars({
      context(pagePath) {
        return pageData[pagePath];
      },
    }),
  ],
};

Partials

If you want to make use of partials in your HTML files, you must define the partialDirectory option for the handlebars plugin.

// vite.config.js
import { resolve } from 'path';
import handlebars from 'vite-plugin-handlebars';

export default {
  plugins: [
    handlebars({
      partialDirectory: resolve(__dirname, 'partials'),
    }),
  ],
};

If you want to use multiple partial folders, an array can be submitted.

Each file in these directories (.html or .hbs) will become registered as a partial. The name of the file is used to invoke it. So, with the above configuration and the following files:

<!-- partials/header.hbs -->
<header><a href="/">My Website</a></header>
<!-- index.html -->
{{> header }}

<h1>The Main Page</h1>

Your output website content would become:

<header><a href="/">My Website</a></header>

<h1>The Main Page</h1>

Make sure to review the quirks section for information on potentially-unexpected behavior.

Helpers

Custom helpers can be registered using the helpers configuration option:

// vite.config.js
import { resolve } from 'path';
import handlebars from 'vite-plugin-handlebars';

export default {
  plugins: [
    handlebars({
      helpers: {
        capitalize: (value) => value.toUpperCase(),
      },
    }),
  ],
};

For more information on helpers, see the Handlebars documentation.

Other Handlebars Options

All other Handlebars configuration options can also be passed through.

Each of these can also be passed through to the handlebars plugin:

// vite.config.js
import handlebars from 'vite-plugin-handlebars';

export default {
  plugins: [
    handlebars({
      compileOptions: {
        // Example config option: avoid auto-indenting partials
        preventIndent: true,
      },
      runtimeOptions: {
        // Example config option: define custom private @variables
        data: {
          foo: 'bar',
        },
      },
    }),
  ],
};

Disabling Browser Refresh on Partial Change

By default, any time a partial changes, your browser window will be full reloaded. If you want to disable this behavior, you can set reloadOnPartialChange to false:

// vite.config.js
import handlebars from 'vite-plugin-handlebars';

export default {
  plugins: [
    handlebars({
      reloadOnPartialChange: false,
    }),
  ],
};

Built-In Helpers

resolve-from-root

You can resolve a file path relative to the Vite root using the resolve-from-root helper. This assists with injecting other files, like linking to a CSS file, within a partial.

<!-- partials/head.hbs -->
<link rel="stylesheet" href="{{resolve-from-root 'css/global.css'}}" />

Quirks

  • Assets included in a partial using a relative path will probably not work how you would first expect; the relative path is left alone, making it relative to the output file, not the partial itself. It's recommended that you use the resolve-from-root helper to ensure paths are resolved from the project root, rather than relative to a particular file.

Author: alexlafroscia
Source code: https://github.com/alexlafroscia/vite-plugin-handlebars
License:

#vite #typescript #javascript #html 

What is GEEK

Buddha Community

Vite Plugin Handlebars : Process HTML Files with Handlebars
Conor  Grady

Conor Grady

1656734400

Vite Plugin Handlebars : Process HTML Files with Handlebars

vite-plugin-handlebars

Vite support for Handlebars

Why?

I really like Vite as a simple static site bundler. It can handle bundling multiple HTML files, which is great, but lacks the ability out-of-the-box to share parts of those HTML files.

While a JS framework like React or Vue could be used to solve this problem, this is heavy-handed for a simple site that could be completely pre-rendered without a JS run-time of any kind.

Handlebars provides what we need to be able to stitch together multiple HTML files, interpolate variables, etc.

Installation

Start by installing the package like you would any other

yarn add -D vite-plugin-handlebars

It can then be added to your Vite configuration as a plugin:

// vite.config.js
import handlebars from 'vite-plugin-handlebars';

export default {
  plugins: [handlebars()],
};

Configuring the plugin is covered later in this guide.

Requirements

  • This plugin is intended to work with Vite 2
  • This plugin requires Node 14 or higher (due to usage of fs/promises)

Configuration

Defining Context

If you want to make use of Handlebars Context to inject variables into your HTML file, you'll need to define their values in the context object passed to the handlebars plugin:

<!-- index.html -->
<h1>{{title}}</h1>
// vite.config.js
import handlebars from 'vite-plugin-handlebars';

export default {
  plugins: [
    handlebars({
      context: {
        title: 'Hello, world!',
      },
    }),
  ],
};

This will result in <h1>Hello, world!</h1> in your output HTML file.

You can also provide a (asynchronous) function, either as the context key or any of the keys within the object, which will be evaluated to create the value that will be made available inside your page. This function is called with an identifier parameter based on the HTML file path which makes it possible to provide unique data to each HTML page in a multipage application setup.

// vite.config.js
import handlebars from 'vite-plugin-handlebars';

const pageData = {
  '/index.html': {
    title: 'Main Page',
  },
  '/nested/subpage.html': {
    title: 'Sub Page',
  },
};

export default {
  plugins: [
    handlebars({
      context(pagePath) {
        return pageData[pagePath];
      },
    }),
  ],
};

Partials

If you want to make use of partials in your HTML files, you must define the partialDirectory option for the handlebars plugin.

// vite.config.js
import { resolve } from 'path';
import handlebars from 'vite-plugin-handlebars';

export default {
  plugins: [
    handlebars({
      partialDirectory: resolve(__dirname, 'partials'),
    }),
  ],
};

If you want to use multiple partial folders, an array can be submitted.

Each file in these directories (.html or .hbs) will become registered as a partial. The name of the file is used to invoke it. So, with the above configuration and the following files:

<!-- partials/header.hbs -->
<header><a href="/">My Website</a></header>
<!-- index.html -->
{{> header }}

<h1>The Main Page</h1>

Your output website content would become:

<header><a href="/">My Website</a></header>

<h1>The Main Page</h1>

Make sure to review the quirks section for information on potentially-unexpected behavior.

Helpers

Custom helpers can be registered using the helpers configuration option:

// vite.config.js
import { resolve } from 'path';
import handlebars from 'vite-plugin-handlebars';

export default {
  plugins: [
    handlebars({
      helpers: {
        capitalize: (value) => value.toUpperCase(),
      },
    }),
  ],
};

For more information on helpers, see the Handlebars documentation.

Other Handlebars Options

All other Handlebars configuration options can also be passed through.

Each of these can also be passed through to the handlebars plugin:

// vite.config.js
import handlebars from 'vite-plugin-handlebars';

export default {
  plugins: [
    handlebars({
      compileOptions: {
        // Example config option: avoid auto-indenting partials
        preventIndent: true,
      },
      runtimeOptions: {
        // Example config option: define custom private @variables
        data: {
          foo: 'bar',
        },
      },
    }),
  ],
};

Disabling Browser Refresh on Partial Change

By default, any time a partial changes, your browser window will be full reloaded. If you want to disable this behavior, you can set reloadOnPartialChange to false:

// vite.config.js
import handlebars from 'vite-plugin-handlebars';

export default {
  plugins: [
    handlebars({
      reloadOnPartialChange: false,
    }),
  ],
};

Built-In Helpers

resolve-from-root

You can resolve a file path relative to the Vite root using the resolve-from-root helper. This assists with injecting other files, like linking to a CSS file, within a partial.

<!-- partials/head.hbs -->
<link rel="stylesheet" href="{{resolve-from-root 'css/global.css'}}" />

Quirks

  • Assets included in a partial using a relative path will probably not work how you would first expect; the relative path is left alone, making it relative to the output file, not the partial itself. It's recommended that you use the resolve-from-root helper to ensure paths are resolved from the project root, rather than relative to a particular file.

Author: alexlafroscia
Source code: https://github.com/alexlafroscia/vite-plugin-handlebars
License:

#vite #typescript #javascript #html 

Conor  Grady

Conor Grady

1656712800

Vite Plugin Html: A Vite Plugin for Processing Html

vite-plugin-html

English | 中文

Features

  • HTML compression capability
  • EJS template capability
  • Multi-page application support
  • Support custom entry
  • Support custom template

Install (yarn or npm)

node version: >=12.0.0

vite version: >=2.0.0

yarn add vite-plugin-html -D

npm i vite-plugin-html -D

Usage

  • Add EJS tags to index.html, e.g.
<head>
  <meta charset="UTF-8" />
  <link rel="icon" href="/favicon.ico" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title><%- title %></title>
  <%- injectScript %>
</head>
  • Configure in vite.config.ts, this method can introduce the required functions as needed
import { defineConfig, Plugin } from 'vite'
import vue from '@vitejs/plugin-vue'

import { createHtmlPlugin } from 'vite-plugin-html'

export default defineConfig({
  plugins: [
    vue(),
    createHtmlPlugin({
      minify: true,
      /**
       * After writing entry here, you will not need to add script tags in `index.html`, the original tags need to be deleted
       * @default src/main.ts
       */
      entry: 'src/main.ts',
      /**
       * If you want to store `index.html` in the specified folder, you can modify it, otherwise no configuration is required
       * @default index.html
       */
      template: 'public/index.html',

      /**
       * Data that needs to be injected into the index.html ejs template
       */
      inject: {
        data: {
          title: 'index',
          injectScript: `<script src="./inject.js"></script>`,
        },
        tags: [
          {
            injectTo: 'body-prepend',
            tag: 'div',
            attrs: {
              id: 'tag',
            },
          },
        ],
      },
    }),
  ],
})

Multi-page application configuration

import { defineConfig } from 'vite'
import { createHtmlPlugin } from 'vite-plugin-html'

export default defineConfig({
  plugins: [
    createHtmlPlugin({
      minify: true,
      pages: [
        {
          entry: 'src/main.ts',
          filename: 'index.html',
          template: 'public/index.html',
          injectOptions: {
            data: {
              title: 'index',
              injectScript: `<script src="./inject.js"></script>`,
            },
            tags: [
              {
                injectTo: 'body-prepend',
                tag: 'div',
                attrs: {
                  id: 'tag1',
                },
              },
            ],
          },
        },
        {
          entry: 'src/other-main.ts',
          filename: 'other.html',
          template: 'public/other.html',
          injectOptions: {
            data: {
              title: 'other page',
              injectScript: `<script src="./inject.js"></script>`,
            },
            tags: [
              {
                injectTo: 'body-prepend',
                tag: 'div',
                attrs: {
                  id: 'tag2',
                },
              },
            ],
          },
        },
      ],
    }),
  ],
})

Parameter Description

createHtmlPlugin(options: UserOptions)

UserOptions

ParameterTypesDefaultDescription
entrystringsrc/main.tsentry file path
templatestringindex.htmlrelative path to the template
injectInjectOptions-Data injected into HTML
minifyboolean|MinifyOptions-whether to compress html
pagesPageOption-Multi-page configuration

InjectOptions

ParameterTypesDefaultDescription
dataRecord<string, any>-injected data
ejsOptionsEJSOptions-ejs configuration OptionsEJSOptions
tagsHtmlTagDescriptor-List of tags to inject

data can be accessed in html using the ejs template syntax

Env inject

By default, the contents of the .env file will be injected into index.html, similar to vite's loadEnv function

PageOption

ParameterTypesDefaultDescription
filenamestring-html file name
templatestringindex.htmlrelative path to the template
entrystringsrc/main.tsentry file path
injectOptionsInjectOptions-Data injected into HTML

MinifyOptions

Default compression configuration

    collapseWhitespace: true,
    keepClosingSlash: true,
    removeComments: true,
    removeRedundantAttributes: true,
    removeScriptTypeAttributes: true,
    removeStyleLinkTypeAttributes: true,
    useShortDoctype: true,
    minifyCSS: true,

Run the playground

pnpm install

# spa
cd ./packages/playground/basic

pnpm run dev

# map
cd ./packages/playground/mpa

pnpm run dev

Example project

Vben Admin


Author: vbenjs
Source code: https://github.com/vbenjs/vite-plugin-html
License: MIT license

#vite #typescript #html 

Ava Watson

Ava Watson

1595318322

Know Everything About HTML With HTML Experts

HTML stands for a hypertext markup language. For the designs to be displayed in web browser HTML is the markup language. Technologies like Cascading style sheets (CSS) and scripting languages such as JavaScript assist HTML. With the help of HTML websites and the web, designs are created. Html has a wide range of academic applications. HTML has a series of elements. HTML helps to display web content. Its elements tell the web how to display the contents.

The document component of HTML is known as an HTML element. HTML element helps in displaying the web pages. An HTML document is a mixture of text nodes and HTML elements.

Basics of HTML are-

The simple fundamental components oh HTML is

  1. Head- the setup information for the program and web pages is carried in the head
  2. Body- the actual substance that is to be shown on the web page is carried in the body
  3. HTML- information starts and ends with and labels.
  4. Comments- come up in between

Html versions timeline

  1. HTML was created in 1990. Html is a program that is updated regularly. the timeline for the HTML versions is
  2. HTML 2- November, 1995
  3. HTML 3- January, 1997
  4. HTML 4- December, 1997; April, 1998; December, 1999; May, 2000
  5. HTML 5- October, 2014; November, 2016; December, 2017

HTML draft version timelines are

  1. October 1991
  2. June 1992
  3. November 1992
  4. June 1993
  5. November 1993
  6. November 1994
  7. April 1995
  8. January 2008
  9. HTML 5-
    2011, last call
    2012 candidate recommendation
    2014 proposed recommendation and recommendation

HTML helps in creating web pages. In web pages, there are texts, pictures, colouring schemes, tables, and a variety of other things. HTML allows all these on a web page.
There are a lot of attributes in HTML. It may get difficult to memorize these attributes. HTML is a tricky concept. Sometimes it gets difficult to find a single mistake that doesn’t let the web page function properly.

Many minor things are to be kept in mind in HTML. To complete an HTML assignment, it is always advisable to seek help from online experts. These experts are well trained and acknowledged with the subject. They provide quality content within the prescribed deadline. With several positive reviews, the online expert help for HTML assignment is highly recommended.

#html assignment help #html assignment writing help #online html assignment writing help #html assignment help service online #what is html #about html

Alisha  Larkin

Alisha Larkin

1617789060

HTML Tutorial For Beginners

The prospect of learning HTML can seem confusing at first: where to begin, what to learn, the best ways to learn — it can be difficult to get started. In this article, we’ll explore the best ways for learning HTML to assist you on your programming journey.

What is HTML?

Hypertext Markup Language (HTML) is the standard markup language for documents meant to be displayed in a web browser. Along with Cascading Style Sheets (CSS) and JavaScript, HTML completes the trio of essential tools used in creating modern web documents.

HTML provides the structure of a webpage, from the header and footer sections to paragraphs of text, videos, and images. CSS allows you to set the visual properties of different HTML elements, like changing colors, setting the order of blocks on the screen, and defining which elements to display. JavaScript automates changes to HTML and CSS, for example, making the font larger in a paragraph when a user clicks a button on the page.

#html #html-css #html-fundamentals #learning-html #html-css-basics #html-templates

ashika eliza

1625652623

HTML - A Complete Guide to Master the Top Programming Language

In this era of technology, anything digital holds a prime significance in our day-to-day life. Hence, developers have submerged themselves to create a major impact using programming languages.According to Statista, HTML/CSS holds the second position (the first being Javascript), in the list of most widely-used programming languages globally (2020).Interested to learn this language? Then head on to this tutorial and get to know all about HTML! Plus we have added numerous examples such that you can learn better! So happy learning!
html for beginners

#html #html-for-beginners #html-tutorials #introduction-to-html #learn-html #tutorials-html