Setup VueJs with Webpack 4

There are many online tools such as vue-cli to quick start to a Vue project. Of cause it saves a lot of time and does not require setting up any dependencies. This post is basically to understand how things work. Before starting, make sure you have installed the Node.js to your system.

Table of Content

Install Dev Dependencies

Let’s start with the installation of the core functionality. We are talking about webpack and the webpack-cli. We are also including the webpack-dev-server in the dependencies installation. The webpack-dev-server provides the functionality to live reload the browser every time a file changes.

Webpack

npm i -D webpack webpack-dev-server webpack-cli

The next step is to install the babel. It is a javascript compiler that converts the ECMAScript 2015+ code into the backward-compatible version of javascript. We will install the @babel/cli, @babel/core, @babel/preset-env and babel-loader.

Babel

npm i -D @babel/cli @babel/core @babel/preset-env babel-loader

The next step is to install the other but powerful dependencies such as vue-loader and vue-template-compiler ( So that the webpack can understand and transpile the javascript files with the .vue extension ), css-loader and vue-style-loader so we can use the CSS style tags in the Vue files, and the html-webpack-plugin is used to generate or specify existing HTML file to serve our bundles.

Others dependencies

npm i -D html-webpack-plugin vue-loader vue-template-compiler css-loader vue-style-loader

Install VueJs

Now install the Vue.

npm i vue

Configure webpack.config.js file

The first step is to include the required and installed dependencies plugin i.e. VueLoaderPlugin, HotModuleReplacementPlugin, and HTMLWebpackPlugin.

const { join } = require('path');
const { VueLoaderPlugin } = require('vue-loader');
const { HotModuleReplacementPlugin } = require('webpack');
const HTMLWebpackPlugin = require('html-webpack-plugin');

The next step is to define the entry and the output file. The entry is the app.js file which is located at the root of your project folder.

module.exports = {
    entry: join(__dirname, 'app.js'), 
    output: {
        path: join(__dirname, 'build'), 
        filename: 'app.min.js'
    }
}

The next step is to include the loaders with some defined rules.

module.exports = {
    entry: join(__dirname, 'app.js'), 
    output: {
        path: join(__dirname, 'build'), 
        filename: 'app.min.js'
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                loader: 'babel-loader',
                options: {
                    presets: ['@babel/preset-env']
                }
            }, {
                test: /.vue$/, 
                loader: 'vue-loader'
            },
            {
                test: /\.css$/, 
                use: [
                    'vue-style-loader',
                    'css-loader'
                ]
            }
        ]
    }
}

The final step is to add the loaded plugins to our webpack.config.js file.

const { join } = require('path');
const { VueLoaderPlugin } = require('vue-loader');
const { HotModuleReplacementPlugin } = require('webpack');
const HTMLWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    entry: join(__dirname, 'app.js'), 
    output: {
        path: join(__dirname, 'build'), 
        filename: 'app.min.js'
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                loader: 'babel-loader',
                options: {
                    presets: ['@babel/preset-env']
                }
            }, {
                test: /.vue$/, 
                loader: 'vue-loader'
            },
            {
                test: /\.css$/, 
                use: [
                    'vue-style-loader',
                    'css-loader'
                ]
            }
        ]
    },
    plugins: [
        new HotModuleReplacementPlugin(),
        new VueLoaderPlugin(),
        new HTMLWebpackPlugin({
            showErrors: true,
            cache: true,
            template: join(__dirname, 'index.html')
        })
    ]
};

Now open the package.json file and add the script start to the file.

"scripts": {
    "start": "npm run dev", 
    "dev": "webpack-dev-server --mode development",
    "prod": "webpack --mode production"
},

The complete package.json file should look like the below file.

{
  "name": "webpack-vuejs",
  "version": "1.0.0",
  "description": "Webpack and Vuejs Setup",
  "scripts": {
    "start": "npm run dev", 
    "dev": "webpack-dev-server --mode development",
    "prod": "webpack --mode production"
  },
  "keywords": [],
  "license": "ISC",
  "devDependencies": {
    "@babel/cli": "^7.8.4",
    "@babel/core": "^7.8.7",
    "@babel/preset-env": "^7.8.7",
    "babel-loader": "^8.0.6",
    "css-loader": "^3.4.2",
    "html-webpack-plugin": "^3.2.0",
    "vue-loader": "^15.9.0",
    "vue-style-loader": "^4.1.2",
    "vue-template-compiler": "^2.6.11",
    "webpack": "^4.42.0",
    "webpack-cli": "^3.3.11",
    "webpack-dev-server": "^3.10.3"
  },
  "dependencies": {
    "vue": "^2.6.11"
  }
}

Now let’s create an index.html file to the root of the project folder. I have added the Bootstrap CSS file to the index.html file.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vue + Webpack 4</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
</head>
<body>
    <div id="app">
        <div class="container">
            <div class="row my-5 justify-content-center">
                <div class="col-sm-6">
                    <h1 class="text-center">{{ message }}</h1>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

Start your Vue App

Let’s create the app.js file to the root directory and add the following code.

import Vue from 'vue';

new Vue({
    el: '#app', 
    data: {
        message: 'Hello from Webpack'
    }
});

Now start the webpack dev server by running the npm start command.

You are using the runtime-only build of Vue where the template compiler is not available

If you are getting the above error then you have to add the resolver to the webpack.config.js file.

module.exports = {
    ....
    module: {
        ....
    },
    resolve: {
        alias: {
          'vue$': 'vue/dist/vue.esm.js'
        },
        extensions: ['*', '.js', '.vue', '.json']
    },
    plugins: [
        ....
    ]
};

You should get the following output.

Create your first Vue Component

Time to create your first component and see if everything works fine. Create a components directory to your root directory and add a file with HelloComponent.vue file.

<template>
    <h2 class="text-center">Hello From Component</h2>
</template>
<script>
export default {
    
}
</script>

Now open the app.js file and attach your HelloComponent with Vue.Component().

import Vue from 'vue';

Vue.component('hello-component', require('./components/HelloComponent').default);

new Vue({
    el: '#app', 
    data: {
        message: 'Hello from Webpack'
    }
});

Now load your component <hello-component> to the index.html file and hit save.

<div id="app">
    <div class="container">
        <div class="row my-5 justify-content-center">
            <div class="col-sm-6">
                <h1 class="text-center">{{ message }}</h1>
                <hello-component />
            </div>
        </div>
    </div>
</div>

Please share if you like this post and if you have any questions or suggestions, please feel free to use the comment section.

Posted by Jogesh Sharma

Jogesh Sharma is a web developer and blogger who loves all the things design and the technology, He love all the things having to do with PHP, WordPress, Joomla, Magento, Durpal, Codeigniter, jQuery, HTML5 etc. He is the author of this blog.