Overview
vue-template-loader is a tool for Vue.js 2.0 that pre-compiles HTML templates into render functions using the vue-template-compiler. It supports features such as scoped CSS, CSS modules, HMR (Hot Module Replacement) support, and decorator syntax for class-style components.
Features
- Transforms HTML templates into render functions
- Supports scoped CSS and CSS modules
- Provides HMR support for templates
- Allows the use of decorator syntax
- Enables functional component templates
Installation
To install vue-template-loader, you can add it as a loader to your webpack configuration:
module.exports = {
// ... other webpack configuration options
module: {
rules: [
// ... other rules
{
test: /\.html$/,
loader: 'vue-template-loader'
}
]
}
}
In order to transform asset paths in your templates to require expressions that webpack can handle, you can configure the transformAssetUrls option. For example, to process image files in the src attribute of <img> elements:
module.exports = {
// ... other webpack configuration options
module: {
rules: [
// ... other rules
{
test: /\.html$/,
loader: 'vue-template-loader',
options: {
transformAssetUrls: {
img: 'src'
}
}
}
]
}
}
To use functional component templates, you need to set the functional option to true in the loader options. You can handle both normal and functional template configs using the oneOf rule:
module.exports = {
// ... other webpack configuration options
module: {
rules: [
// ... other rules
{
test: /\.html$/,
loader: 'vue-template-loader',
options: {
functional: true
}
}
]
}
}
For loading scoped styles, you need to import the HTML and style files using the following syntax:
import withRender from './app.html?style=./app.css'
You also need to modify your webpack config as follows:
- Set
scoped: truein thevue-template-loaderoptions. - Mark some of your style loaders (usually style-loader and css-loader) as post-loaders by setting
enforce: 'post'.
module.exports = {
// ... other webpack configuration options
module: {
rules: [
// ... other rules
{
test: /\.html$/,
loader: 'vue-template-loader',
options: {
scoped: true
}
},
{
test: /\.css$/,
loader: 'style-loader',
enforce: 'post'
},
// ... other style loaders (e.g., css-loader) marked as post loaders
]
}
}
To style children components or third party components, you can use the >>> combinator. Note that currently, the >>> operator is not supported in Less, but an alternative can be used.
For loading CSS modules, you can use the loader syntax:
import withRender from './app.html?style=./app.css'
You also need to enable the modules flag of css-loader.
Summary
vue-template-loader is a helpful tool for pre-compiling HTML templates into render functions in Vue.js 2.0. It provides various features such as scoped CSS, CSS modules, HMR support, and decorator syntax. The installation and configuration process involves adding it as a loader in your webpack configuration and modifying the necessary options for scoped styles and CSS modules.