Vue.js 2.0 template loader for webpack
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.
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:
scoped: true in the vue-template-loader options.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.
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.