Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 38 ยท Webpack with Frameworks

Webpack with Vue and Svelte

Configure webpack for Vue single-file components with vue-loader and VueLoaderPlugin, and for Svelte with svelte-loader. Learn how SFC blocks are split, styled and hot reloaded.

Vue and Svelte both let you write a component in one file that mixes markup, logic and styles. A browser cannot read those files, so webpack uses a framework loader to split and compile them: vue-loader for Vue single-file components (.vue) and svelte-loader for .svelte files. Once the loader has run, the pieces look like ordinary JavaScript and CSS and flow through the rest of your pipeline.

This lesson shows the configuration for both, explains the idea of splitting an SFC into blocks that are routed to other loaders, and covers hot reload, scoped styles and lazy components.

Webpack, Vue and Svelte cannot run on this site, so configuration and component code are read-only. The TryIt blocks are Node.js stand-ins: one splits a single-file component into blocks (the first step of vue-loader), and one mimics how scoped styles get attribute selectors.

Vue with vue-loader

Terminal
npm install vue
npm install -D webpack webpack-cli webpack-dev-server vue-loader \
  css-loader style-loader html-webpack-plugin
JavaScript
// webpack.config.js (read-only example)
const { VueLoaderPlugin } = require('vue-loader');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  mode: 'development',
  entry: './src/main.js',
  resolve: { extensions: ['.js', '.vue'] },
  module: {
    rules: [
      { test: /\.vue$/, loader: 'vue-loader' },
      { test: /\.css$/, use: ['style-loader', 'css-loader'] },
      { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' },
    ],
  },
  plugins: [
    new VueLoaderPlugin(),
    new HtmlWebpackPlugin({ template: './public/index.html' }),
  ],
  devServer: { hot: true, historyApiFallback: true },
};

VueLoaderPlugin is mandatory: it clones your other rules so they also apply to the <script> and <style> blocks inside .vue files. Without it, a rule for .css would not touch a <style> block and you get confusing errors.

How an SFC is split

A single-file component looks like this:

VUE
<template>
  <button class="btn" @click="count++">Clicked {{ count }} times</button>
</template>

<script setup>
import { ref } from 'vue';
const count = ref(0);
</script>

<style scoped>
.btn { background: tomato; color: white; }
</style>

vue-loader parses the file into blocks (template, script, style). It rewrites each block into a request with a query, such as ./Button.vue?vue&type=style&index=0&scoped=true&lang=css, and webpack runs that request through the normal rules. That is why your CSS, Sass or TypeScript loaders work inside components with no extra work.

Node.js Stand-in: split a single-file component

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Each generated request is a module of its own, which is what allows webpack to hot-update only the style or only the template when you edit it.

Scoped styles

With <style scoped>, Vue adds a unique data attribute to the component's elements and rewrites selectors so they only match elements that carry it. Your .btn rule affects this component's buttons only.

Node.js Stand-in: how scoped CSS selectors are rewritten

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Vue feature flags

Vue 3's bundler build reads a few compile-time flags. Define them to avoid warnings and to shrink production bundles:

JavaScript
const webpack = require('webpack');

plugins: [
  new webpack.DefinePlugin({
    __VUE_OPTIONS_API__: JSON.stringify(true),   // set false if you only use <script setup>
    __VUE_PROD_DEVTOOLS__: JSON.stringify(false),
    __VUE_PROD_HYDRATION_MISMATCH_DETAILS__: JSON.stringify(false),
  }),
],

Turning __VUE_OPTIONS_API__ off lets tree shaking drop the Options API support if your whole app uses the Composition API.

Lazy Vue components

JavaScript
import { defineAsyncComponent } from 'vue';

export default {
  components: {
    AdminChart: defineAsyncComponent(() =>
      import(/* webpackChunkName: "admin-chart" */ './AdminChart.vue'),
    ),
  },
};

Vue Router uses the same pattern: component: () => import('./views/Reports.vue'). This relies on dynamic imports. See the Vue.js tutorial for the framework itself.

Svelte with svelte-loader

Terminal
npm install -D svelte svelte-loader webpack webpack-cli
JavaScript
// webpack.config.js (read-only example)
const path = require('path');

module.exports = {
  entry: './src/main.js',
  resolve: {
    alias: { svelte: path.dirname(require.resolve('svelte/package.json')) },
    extensions: ['.mjs', '.js', '.svelte'],
    mainFields: ['svelte', 'browser', 'module', 'main'],
    conditionNames: ['svelte', 'browser', 'import'],
  },
  module: {
    rules: [
      {
        test: /\.svelte$/,
        use: {
          loader: 'svelte-loader',
          options: { compilerOptions: { dev: process.env.NODE_ENV !== 'production' }, emitCss: true, hotReload: true },
        },
      },
      { test: /\.css$/, use: ['style-loader', 'css-loader'] },
    ],
  },
};

The Svelte compiler turns each component into plain JavaScript that updates the DOM directly, with no runtime virtual DOM. emitCss: true hands the component's styles to your CSS loaders. mainFields and conditionNames tell webpack to prefer the svelte field of library package.json files, which lets Svelte libraries ship uncompiled .svelte source. Details of the language are in the Svelte tutorial.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is VueLoaderPlugin needed for?

    The plugin clones matching rules so that blocks inside single-file components are processed by the same loaders as normal files.
  2. 2. How does vue-loader hand a <style> block to css-loader?

    Each block becomes a virtual request with a query, which webpack resolves through the normal rules.
  3. 3. What do scoped styles do?

    Selectors are rewritten with a data attribute so rules match only elements rendered by the same component.
  4. 4. Why set mainFields/conditionNames to include 'svelte'?

    Svelte libraries may expose a 'svelte' entry pointing at uncompiled components that your loader compiles.

Summary

  • vue-loader splits .vue files into blocks and routes each through your normal loaders; VueLoaderPlugin is required.
  • Scoped styles work by attribute selectors added at build time.
  • Define Vue's feature flags to remove unused code in production.
  • svelte-loader compiles components to plain JS, with options for CSS emission and hot reload.
  • Lazy components use import() and give you route-level chunks.

Next: Webpack with TypeScript