Setup VueJs with Webpack 4

栏目: IT技术 · 发布时间: 5年前

内容简介:There are many online tools such asLet’s start with the installation of the core functionality. We are talking aboutThe next step is to install the babel. It is a javascript compiler that converts the ECMAScript 2015+ code into the backward-compatible vers

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. The post is to understand how things work. Before starting, make sure you have installed the Node.js to your system.

Table of Content

  • Install Dev Dependencies
  • Configure webpack.config.js file
  • Create your first Vue Component

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>
            <div>
                <div>
                    <h1>{{ 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.

Setup VueJs with Webpack 4

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>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>
        <div>
            <div>
                <h1>{{ message }}</h1>
                <hello-component />
            </div>
        </div>
    </div>
</div>
Setup VueJs with Webpack 4

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


以上所述就是小编给大家介绍的《Setup VueJs with Webpack 4》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

新物种爆炸

新物种爆炸

吴声 / 中信出版社 / 2017-7-30 / 58.00元

宝马为什么要重点发展共享汽车 Airbnb正试图成为内容和社交平台 不排队、不结账、没有收银员的颠覆传统超市 茑屋书店要打造全新生活方式 基于新的商业环境与技术条件的变化,必须会产生新的品类和商业模式,这就是新物种! 大数据与人工智能等技术正在创建新的商业话语体系,创建新的权力架构,引领第四新物种爆炸。商业规则正在快速发生变化,新的模式与业态层出不穷。 要么成为......一起来看看 《新物种爆炸》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换