vue-loader Documentation

website·Indexed 19 days ago

https://vue-loader.vuejs.org/

Documentation for vue-loader, including guides on Scoped CSS, CSS Modules, CSS Extraction, Hot Reload, and Asset URL Handling. It covers the Vue Single-File Component (SFC) Spec, custom blocks, linting, and migration from v14.

Tokens
7.2K
Snippets
43
Records
62
Agent score
96%

What's inside vue-loader

  1. Handle asset URLs in Vue SFC templates

    When Vue Loader compiles <template> blocks in Single File Components (SFCs), it converts asset URLs into webpack module requests (using require()). This allows webpack to process assets via loaders like file-loader or url-loader for version hashing and caching.

    By default, the following tag and attribute combinations are transformed:

    • video: src, poster
    • source: src
    • img: src
    • image: xlink:href, href
    • use: xlink:href, href

    These defaults can be customized using the transformAssetUrls option.

    <!-- Input -->
    <img src="../image.png">
    
    <!-- Compiled Output -->
    createElement('img', {
      attrs: {
        src: require('../image.png')
      }
    })
  2. Understand the purpose of vue-loader

    vue-loader is a webpack loader that enables the use of Single-File Components (SFCs). It allows developers to encapsulate the template, logic (script), and styling (style) of a Vue component within a single .vue file. Key capabilities include:

    • Integration with other webpack loaders (e.g., Sass for styles, Pug for templates).
    • Support for custom blocks within .vue files with dedicated loader chains.
    • Treatment of static assets in templates and styles as module dependencies.
    • Simulation of scoped CSS for component-level styling.
    • State-preserving hot-reloading during development.
    <template>
      <div class="example">{{ msg }}</div>
    </template>
    
    <script>
    export default {
      data () {
        return {
          msg: 'Hello world!'
        }
      }
    }
    </script>
    
    <style>
    .example {
      color: red;
    }
    </style>
  3. Vue Single-File Component (SFC) structure overview

    A .vue file is a custom format using HTML-like syntax to describe a Vue component. It consists of three primary top-level language blocks: <template>, <script>, and <style>, and optionally custom blocks. vue-loader parses these blocks and assembles them into an ES Module where the default export is a Vue.js component options object.
    <template>
      <div class="example">{{ msg }}</div>
    </template>
    
    <script>
    export default {
      data () {
        return {
          msg: 'Hello world!'
        }
      }
    }
    </script>
    
    <style>
    .example {
      color: red;
    }
    </style>
    
    <custom1>
      This could be e.g. documentation for the component.
    </custom1>
  4. Lint Vue styles with stylelint

    Use stylelint to lint the style blocks within Vue single file components. After configuring stylelint, you can run it directly from the command line against .vue files.
    stylelint MyComponent.vue
  5. Extract CSS in webpack 4 for production

    To extract CSS into separate files in webpack 4, use the mini-css-extract-plugin. It is recommended to only apply CSS extraction in production environments to maintain CSS hot reload capabilities during development. In development, vue-style-loader should be used instead of the extraction loader.
    npm install -D mini-css-extract-plugin
    // webpack.config.js
    var MiniCssExtractPlugin = require('mini-css-extract-plugin')
    
    module.exports = {
      module: {
        rules: [
          {
            test: /\.css$/,
            use: [
              process.env.NODE_ENV !== 'production'
                ? 'vue-style-loader'
                : MiniCssExtractPlugin.loader,
              'css-loader'
            ]
          }
        ]
      },
      plugins: [
        new MiniCssExtractPlugin({
          filename: 'style.css'
        })
      ]
    }
  6. Install and configure VueLoaderPlugin for v15

    Vue Loader v15 now requires the VueLoaderPlugin to be added to the webpack plugins array to function properly.
    // webpack.config.js
    const { VueLoaderPlugin } = require('vue-loader')
    
    module.exports = {
      // ...
      plugins: [
        new VueLoaderPlugin()
      ]
    }
  7. Define and process custom blocks in .vue files

    You can define custom language blocks inside *.vue files. These blocks are processed by webpack loaders based on the block's tag name, the lang attribute, and your webpack configuration rules.

    • With lang attribute: If a lang attribute is specified, the block is matched as if it were a file with that language as its extension.
    • Without lang attribute: You can use resourceQuery in your webpack config to match specific custom block tags (e.g., matching <foo> blocks using /blockType=foo/).

    If no matching rule is found, the custom block is silently ignored. If the processing loaders export a function as the final result, that function is called with the component of the *.vue file as its parameter.

    // Example: Matching <foo> custom blocks in webpack.config.js
    {
      module: {
        rules: [
          {
            resourceQuery: /blockType=foo/,
            loader: 'loader-to-use'
          }
        ]
      }
    }
  8. Apply scoped styles to child components using deep selectors

    By default, scoped styles do not leak into child components (except for the child's root node). To affect elements inside a child component, use a 'deep selector'. The >>> combinator is the standard approach. For pre-processors like Sass that may not support >>>, use the ::v-deep or /deep/ aliases.
    <style scoped>
    /* Standard combinator */
    .a >>> .b { color: red; }
    
    /* Aliases for pre-processors (Sass, etc) */
    .a::v-deep .b { color: red; }
    .a /deep/ .b { color: red; }
    </style>
  9. Configure webpack loaders for asset files

    Since asset extensions (like .png) are not JavaScript modules, you must configure webpack to handle them.

    • Use file-loader to copy assets to a specific location and apply version hashes for caching.
    • Use url-loader to conditionally inline small files as base-64 data URLs to reduce HTTP requests (falling back to file-loader for larger files).

    Note: Projects created with Vue CLI have these loaders pre-configured.

  10. Enable Hot Reload in Vue projects

    Hot Reload is enabled by default in projects scaffolded with vue-cli. For manual project setups, Hot Reload is enabled automatically when serving the project using webpack-dev-server with the --hot flag.
    webpack-dev-server --hot
  11. Integrate PostCSS with Vue Loader

    Vue Loader v15 does not apply PostCSS transforms by default. You must use postcss-loader. To ensure @import statements are processed by PostCSS, set importLoaders: 1 in the css-loader options.
    npm install -D postcss-loader
    // webpack.config.js -> module.rules
    {
      test: /\.css$/,
      use: [
        'vue-style-loader',
        {
          loader: 'css-loader',
          options: { importLoaders: 1 }
        },
        'postcss-loader'
      ]
    }
  12. Use Stylus in Vue components

    Install stylus and stylus-loader, then configure the webpack rule for .styl or .stylus files.
    npm install -D stylus stylus-loader
    // webpack.config.js -> module.rules
    {
      test: /\.styl(us)?$/,
      use: [
        'vue-style-loader',
        'css-loader',
        'stylus-loader'
      ]
    }