• Stars
    star
    267
  • Rank 153,621 (Top 4 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 8 years ago
  • Updated over 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Vue.js 2.0 template loader for webpack

vue-template-loader

Build Status vue-template-loader Dev Token

Vue.js 2.0 template loader for webpack

This loader pre-compiles a html template into a render function using the vue-template-compiler. Each html file is transformed into a function that takes a vue component options object and injects a render function, styles and HMR support.

In most cases, vue-loader is recommended over this loader.

Features

  • Transforms a html template into a render function
  • Supports scoped css and css modules (similar to vue-loader)
  • HMR support for templates
  • Decorator syntax support (can be used with vue-class-component or other class style components)

Webpack Configuration

Loading a Html Template

Add vue-template-loader as a loader to your webpack configuration.

module.exports = {
  module: {
    rules: [
      { test: /\.html$/, use: 'vue-template-loader' }
    ]
  }
}

Asset Transforms

To transform asset paths in your templates to require expressions that webpack can handle, configure the transformAssetUrls option. For example, if you would like webpack to process the image files in the src attribute of <img> elements:

module.exports = {
  module: {
    rules: [
      {
        test: /\.html$/,
        loader: 'vue-template-loader',
        options: {
          transformAssetUrls: {
            // The key should be an element name
            // The value should be an attribute name or an array of attribute names
            img: 'src'
          }
        }
      },

      // Make sure to add a loader that can process the asset files
      {
        test: /\.(png|jpg)/,
        loader: 'file-loader',
        options: {
          // ...
        }
      }
    ]
  }
}

Functional Component

If you want to use functional component template, you need to set functional: true option to loader options. You may want to use oneOf to handle both normal and functional template configs.

module.exports = {
  module: {
    rules: [
      {
        test: /\.html$/,
        oneOf: [
          // If the file name has `.functional` suffix, treat it as functional component template
          // You can change this rule whatever you want.
          {
            test: /\.functional\.html$/,
            loader: 'vue-template-loader',
            options: {
              functional: true
            }
          },

          // Normal component template
          {
            loader : 'vue-template-loader'
          }
        ]
      }
    ]
  }
}

Loading Scoped Styles

For an explanation of scoped styles, see the vue-loader docs.

Html and style files need to be imported using import withRender from './app.html?style=./app.css'.

You also need modify your webpack config as follows:

  • Set scoped: true in the vue-template-loader options
  • Mark some of your style loaders (usually style-loader and css-loader) as post-loaders (by setting enforce: 'post').

Logic for what to mark as a post-loader: vue-template-loader injects an inline webpack loader into your loader pipeline to modify your style files to include [scope-id] selectors. Webpack loaders run in the order normal -> inline -> post, so any loaders you want to run before the inline loader should be normal loaders, and anything you want to run after the inline loader should be post loaders (i.e. marked with enforce: 'post').

Typically you will want to leave loaders that compile to css (like less, sass and postcss transpilers) as normal loaders, so they run before the [scope-id] injection. Loaders that transform css into a format for webpack consumption (like style-loader and css-loader) should be post loaders (marked as enforce: 'post').

module.exports = {
  module: {
    rules: [
      {
        // Loaders that transform css into a format for webpack consumption should be post loaders (enforce: 'post')
        enforce: 'post',
        test: /\.css$/,
        use: ['style-loader', 'css-loader']
      },
      // We needed to split the rule for .scss files across two rules
      {
        // The loaders that compile to css (postcss and sass in this case) should be left as normal loaders
        test: /\.scss$/,
        use: ['postcss-loader', 'sass-loader']
      },
      {
        // The loaders that format css for webpack consumption should be post loaders
        enforce: 'post',
        test: /\.scss$/,
        use: ['style-loader', 'css-loader']
      }
    ]
  }
}

>>> combinator

There are cases where you may want to style children components e.g. using a third party component. In such cases, you can use the >>> (/deep/) combinator to apply styles to any descendant elements of a scoped styled element.

Input:

.foo >>> .bar {
  color: red;
}

Output:

.foo[data-v-4fd8d954] .bar {
  color: red
}

If you are using less, note that it does not yet support the >>> operator, but you can use:

@deep: ~">>>";

.foo @{deep} .bar {
  color: red;
}

Loading CSS Modules

For an explanation of CSS modules, see the vue-loader docs.

Html and style files need to be imported using the loader syntax: import withRender from './app.html?style=./app.css'. You also need to enable the modules flag of css-loader.

vue-template-loader will add the $style property to your view model and you can use hashed classes through it.

module.exports = {
  module: {
    rules: [
      {
        test: /\.html$/,
        use: 'vue-template-loader'
      },
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader?modules'] // Enable CSS Modules
      }
    ]
  }
}

Disabling HMR

By default Hot Module Replacement is disabled in the following situations:

  • Webpack target is node
  • Webpack minifies the code
  • process.env.NODE_ENV === 'production'

You may use the hmr: false option to disable HMR explicitly for any other situation.

module.exports = {
  module: {
    rules: [
      {
        test: /\.html$/,
        loader: 'vue-template-loader',
        options: {
          hmr: false // disables Hot Modules Replacement
        }
      }
    ]
  }
}

Example

Write a template for a Vue component using html.

<!-- app.html -->
<div class="app">
  <p>{{ text }}</p>
  <button type="button" @click="log">Log</button>
</div>

Import it as a function and pass a component option to the function. If you would like to load a style file, add the style query and specify the style file path.

// app.js
import withRender from './app.html?style=./app.css'

export default withRender({
  data () {
    return {
      text: 'Example text'
    }
  },

  methods: {
    log () {
      console.log('output log')
    }
  }
})

You can use decorator syntax for any class style components.

import Vue from 'vue'
import Component from 'vue-class-component'
import WithRender from './app.html'

@WithRender
@Component
export default class App extends Vue {
  text = 'Example text'

  log () {
    console.log('output log')
  }
}

Typescript

If you use this loader with TypeScript, make sure to add a declaration file for html files into your project. (If you want to load style files via query string, you need to replace *.html with *.css)

declare module '*.html' {
  import Vue, { ComponentOptions, FunctionalComponentOptions } from 'vue'
  interface WithRender {
    <V extends Vue, U extends ComponentOptions<V> | FunctionalComponentOptions>(options: U): U
    <V extends typeof Vue>(component: V): V
  }
  const withRender: WithRender
  export default withRender
}

Option Reference

transformAssetUrls

  • type: Object
  • default: {}

To specify which attribute of elements are processed with webpack. Keys are element names while the values are their attribute string or array of string.

functional

  • type: Boolean
  • default: false

Process template as functional component template if it is true.

scoped

  • type: Boolean
  • default: false

If true, styles will be scoped.

hmr

  • type: Boolean
  • default: true

If false, disable hot module replacement.

optimizeSSR

  • type: Boolean
  • default: false

You can enable SSR optimazation when specify this option true.

compiler

  • type: function
  • default: vue-template-compiler

You can override the default compiler using this option.

Templates

There is vue-cli template using vue-template-loader (Thanks to @Toilal).

License

MIT

More Repositories

1

vuex-class

Binding helpers for Vuex and vue-class-component
TypeScript
1,729
star
2

vuex-smart-module

Type safe Vuex module with powerful module features
TypeScript
381
star
3

vue-designer

Vue component design tool
TypeScript
368
star
4

vue-cli-plugin-auto-routing

Automatically resolve pages and layouts routing
JavaScript
296
star
5

vue-auto-routing

Generate Vue Router routing automatically
TypeScript
254
star
6

vuex-connect

A binding utility for a Vue component and a Vuex store.
JavaScript
253
star
7

vue-route-generator

Vue Router route config generator
TypeScript
150
star
8

vue-range-slider

Simple slider component of Vue.js
JavaScript
129
star
9

vue-router-layout

Lightweight layout resolver for Vue Router
TypeScript
126
star
10

vue-thin-modal

Thin yet powerful modal component of Vue.js
JavaScript
124
star
11

vuetype

Generate TypeScript declaration files for .vue files
TypeScript
122
star
12

sinai

Class based state management for Vue
TypeScript
111
star
13

vue-typed-mixins

Type safe Vue.js mixins
JavaScript
107
star
14

vuex-type-helper

Type level helper to ensure type safety in Vuex
TypeScript
104
star
15

vuex-toast

Simple toast notification using Vuex
JavaScript
80
star
16

vuex-local

Local state management within Vuex
TypeScript
64
star
17

vue-size-provider

Declarative element size observer and provider
JavaScript
55
star
18

vuex-assert

Assertion for Vuex state
TypeScript
54
star
19

vuex-reducer

Reducer in Vuex
TypeScript
50
star
20

vue-media-loader

Enable `media` attribute on Vue SFC styles
TypeScript
47
star
21

vue-sfc-parser

Vue.js single file component parser for static analysis
TypeScript
47
star
22

ts-compiler-api-examples

A Collection of example using TypeScript Compiler API
TypeScript
45
star
23

vite-typescript-starter

Starter template for Vite + TypeScript project
Vue
42
star
24

vue-ast-explorer

Vue template AST explorer https://ktsn.github.io/vue-ast-explorer/
Vue
41
star
25

birdseye

Next generation component catalog
TypeScript
39
star
26

svelte-jest

Jest Svelte component transformer
JavaScript
37
star
27

vue-tsx

TSX hook for Vue.js
JavaScript
36
star
28

vue-vnode-helper

Helpers for Vue's createElement inspired by hyperscript-helpers
TypeScript
35
star
29

vue-svelte-adapter

Using Svelte components in Vue.js
TypeScript
32
star
30

vuex-strong-cache

Allow stronger cache for Vuex getters
TypeScript
28
star
31

vue-inversify-decorator

PoC of combining vue-class-component and Inversify together
JavaScript
26
star
32

vue-composable-tester

Utility to test composition api functions for Vue.js
TypeScript
25
star
33

eslint-plugin-vue-composable

ESLint plugin providing Vue composable related rules
TypeScript
25
star
34

css-spring-animation

Intuitive and predictable spring animation library powered by CSS Transition
TypeScript
24
star
35

vue-canvas

Declarative canvas rendering using Vue.js
TypeScript
23
star
36

calendar-set

Framework agnostic calendar components
HTML
20
star
37

vuex-mappers

Component agnostic Vuex mappers
TypeScript
19
star
38

vue-hot-reload-loader

Enable hot module replacement (HMR) on your Vue components
JavaScript
19
star
39

vq

A light-weight and functional animation helper for Velocity.js
JavaScript
19
star
40

template-vue-component

Boilerplate for standalone Vue.js components
JavaScript
16
star
41

vue-form-builder

Form builder on Vue.js
TypeScript
13
star
42

truncator

Layout specific text truncator considering line length, content height or character length.
JavaScript
12
star
43

vuec

CLI compiler of Vue single file component
TypeScript
11
star
44

capture-all

Flexible utility to get screenshots from Web pages
TypeScript
11
star
45

vue-lazy-components-option

Provide lazyComponents option for Vue components
JavaScript
10
star
46

vue-transition-components

Transition component collection of Vue.js
JavaScript
9
star
47

template-nuxt

Minimal project setup using Nuxt.js and TypeScript
JavaScript
8
star
48

vuex-modal

Simple modal component/Vuex module
JavaScript
8
star
49

typescript-webpack-simple

A simple TypeScript + Webpack + vue-loader setup.
Vue
8
star
50

typed-vue-template

Inject Vue template into TypeScript code
TypeScript
7
star
51

vue-cli-plugin-mfc

Vue CLI plugin for multiple file component projects (WIP)
JavaScript
7
star
52

babel-plugin-remove-vue-extend

Babel plugin for removing `Vue.extend` from components
TypeScript
7
star
53

safe-object-proxy

Safe property access for JavaScript objects using Proxy Object
JavaScript
7
star
54

npm-package-example

Example of npm package
JavaScript
6
star
55

learning-typescript

Personal notes to learn TypeScript
6
star
56

lens-proxy

PoC of Proxy implementation of Lens.ts
TypeScript
5
star
57

mirror-tube

The Google Chrome extention that mirrors a YouTube video
JavaScript
5
star
58

hawkeye

Intuitive tab manager for Google Chrome
TypeScript
5
star
59

template-vue

A project template for Vue.js applications
JavaScript
5
star
60

vue-template-diagnostic

Diagnostic for expressions of Vue.js templates
TypeScript
5
star
61

ktsn.art

TypeScript
4
star
62

template-ts

A project template for a TypeScript library
JavaScript
4
star
63

markdown-it-demo-renderer

markdown-it renderer to render live demo over each code block fence
TypeScript
3
star
64

vue-rubberband

Rubberband component of Vue.js
JavaScript
3
star
65

bs-compile-middleware

Compilation middleware for Browsersync
JavaScript
3
star
66

meck

Small and type safe message bus with well module separation
TypeScript
3
star
67

typed-vue-loader

Typed Vue template loader
Vue
2
star
68

vti-demo

Vetur Terminal Interface Demo
Vue
2
star
69

vuex-first-router

PoC of redux-first-router for Vuex and Vue Router
TypeScript
2
star
70

float-behind-client

HTML
2
star
71

vue-loader-custom-block-repro

A reproduction of vue-loader issue
JavaScript
2
star
72

float-behind-lp

The landing page for floatbehind (https://github.com/ktsn/float-behind)
HTML
2
star
73

template-es6

A project template for an ES6 library
JavaScript
2
star
74

selective-undo-text

A Selective Undo library for text editing
TypeScript
1
star
75

vue-deps-perf-demo

JavaScript
1
star
76

template-node-ts

A project template for a Node.js library using TypeScript
JavaScript
1
star
77

.github

1
star
78

jest-config-ktsn

Personal Jest configuration
JavaScript
1
star
79

vue-svg-loader-test

Vue
1
star
80

flip-our-animations

Implementations of FLIP animation for various libraries
JavaScript
1
star
81

ob

A tiny and extensible FRP library
TypeScript
1
star
82

float-behind

Updates chat information automatically behind your desktop
JavaScript
1
star
83

k-css

Reset CSS for easier custom styling
HTML
1
star
84

eslint-config-ktsn-vue

ESLint config for Vue.js project
JavaScript
1
star
85

nuxt-page-transition-example

Page transition example for Nuxt.js https://ktsn.github.io/nuxt-page-transition-example/
Vue
1
star
86

nuxt-scroll-behavior-repro

Reproduction of nuxt scroll behavior issue
Vue
1
star
87

vue-mutation-store

Vuex and Redux inspired MVVM approach for Vue.js. (experimental)
TypeScript
1
star
88

vue-comm

An experiment of Vue.js type safety
TypeScript
1
star
89

vue-custom-properties

Make easier to use CSS custom properties in Vue components
TypeScript
1
star
90

template-node

A project template for Node.js libraries
JavaScript
1
star