Table of Contents
1. Development environment preparation
1.1 Install nodejs
1.2 Using Taobao Npm mirror
1.3 IDE preparation
2. Build a Webpack project
2.1 Create a new project
2.2 Installing Webpack
2.2.1 Installation
2.2.2 Configuration
3、进阶Webpack
3.1 常用插件
3.1.1 Html-webpack-plugin插件
3.1.2 Extract-text-webpack插件
3.2 开发服务器 - Webpack-dev-server
Home Web Front-end JS Tutorial Environment construction method for developing SPA applications using Vue2.X and Webpack2.X

Environment construction method for developing SPA applications using Vue2.X and Webpack2.X

Jul 22, 2017 pm 03:40 PM
web

[TOC]

1. Development environment preparation

1.1 Install nodejs

First install Nodejs, go directly to the nodejs official website to download, Npm will be installed by default, so here you can No separate installation required.

1.2 Using Taobao Npm mirror

Due to domestic network reasons, if you directly use Npm to install dependency packages, it will be unsuccessful due to network and wall reasons. Fortunately, Taobao provided me with one that can be used. Mirror, the address is:, follow its [Instructions] to install the mirror.

1.3 IDE preparation

Currently, the most popular IDE for front-end development is Jetbrain’s WebStorm. Download it from its official website: There is a 30-day trial period after installation. If you feel uncomfortable, you can search online. Crack, here is the registration information I used. Of course the best thing is to pay

2. Build a Webpack project

2.1 Create a new project

When the development environment is ready, you can open WebStorm and create a new empty project. As shown below:

There are many benefits of using webstorm. One of them is that you can directly call up the console in the IDE, as shown below:

Enter "npm init" in the console to initialize the project. The console will ask you to enter the following information. You can press Enter by default here. Finally, enter "yes" as prompted to complete the initialization.

At this time, package.json will be generated in the project root directory. When you open the file, you can see the information just entered in the console, as follows:

The package.json file is Nodejs and Npm searches for a list of dependencies. For more information, please refer to this document: and

2.2 Installing Webpack

For the concept and function of Webpack, please refer to this blog post: https://llp0574.github.io/2016/11/29/getting-started-with-webpack2/?utm_source=tuicool&utm_medium=referraland
. For children's shoes that are good in English, you can directly refer to the official website: http://webpack.github.io/

The purpose of using webpack is to make the code more modular and facilitate maintenance and management. This is the same as using it in Java Maven is very similar to managing packages.

2.2.1 Installation

First, enter the command in the console: npm install webpack. The function of this command is to let npm install webpack under node_modules (the directory will be automatically generated).

  • In the production environment, add --save after the command, for example: npm install webpack --save, which means to install webpack under node_modules and update the package .json file dependencies.

  • In the development environment, we use: npm install webpack --save-dev, install webpack under Node_modules, and update the devDependencies of package.json.
    Here we use the commands in the development environment.

For more NPM commands, please refer to the official website: and

2.2.2 Configuration

1. First, let’s Create a new src directory in the project directory, and create a hello.js file under src. Write the following code in the file:

export default function () {const hello = document.createElement("div");hello.textContent = "Hello Webpack!"return  hello;}
Copy after login

This is implemented according to ES6 syntax.

For more information about ES6, please refer to this document:.

export defines an interface exposed to the outside world, and default provides a default output for export, so that you can customize the variable name when importing without specifying the variable name in the export when importing. So this code means: Enter an anonymous function by default.

2. Then, create main.js under the same level as hello.js, and then enter the following content:

import Hello from "./hello";document.getElementById("app").appendChild(Hello());
Copy after login

import is to import the hello.js just written The file is imported as a module. The "Hello" variable is the variable name defined for this anonymous function. After from is the address of the imported file. If it is a js file, it does not need to be written by default. The path can be a relative path or an absolute path, and then use js Go get the app node from the dom and add child elements.

3. Create a new public folder in the project root directory, and create a new Index.html file, as follows:

Then create a div in the Html file with the id app and add it in the body Introduce script at the end, as shown below:

<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Webpack Example</title><body><div id="app" ></div><script type="text/javascript" src="bundle.js?1.1.11"></script></body></html>
Copy after login

4. Create a new webpack.config.js file in the project directory, edit the webpack.config.js file, and write the following code:

module.exports = {entry: __dirname + "/src/main.js?1.1.11",output: {path: __dirname + "/public",filename: "bundle.js?1.1.11"}}
Copy after login

__dirname是nodejs中的全局变量,指向当前执行脚本的目录。
module.exports是webpack的对象,其中entry是指定入口文件,这里指定main.js为入口文件。output下的path是输出目录,filename是输出文件名称。通过path和filename组合就可以将我们再代码中引入的模块完整的输出到制定的文件中。

5.在控制台执行webpack命令,就可以看到bundle.js文件已经输出到Public目录下了

这个时候通过浏览器打开Index.html可以看到效果:

3、进阶Webpack

上面我们已经可以用webpack来打包我们的模块,不过这只是刚入门,后面我们会不断的完善webpack.config.js这个文件。
从刚才的例子中,我们需要自己手动的在html页面里面引入bundle.js文件,那么有没有自动帮我们引入文件的功能呢?回答肯定是有的,这里就介绍下Html-webpack-plugin插件。

3.1 常用插件

3.1.1 Html-webpack-plugin插件

插件官方地址是:,这里只是简单讲解使用。

1.要使用html插件,首先需要在项目中引入该模块,在控制台执行命令:

npm install html-webpack-plugin --save-dev
Copy after login

2.编辑webpack.config.js文件,在其中加入以下代码:

var HtmlWebpackPlugin = require("html-webpack-plugin");module.exports = {entry: __dirname + "/src/main.js?1.1.11",output: {path: __dirname + "/public",filename: "bundle.js?1.1.11"},plugins: [new HtmlWebpackPlugin()
    ]}
Copy after login

可以看到,使用require引入html-webpack-plugin,然后在配置中的plugins数组中new一个插件对象。

3.这个时候我们把public目录删除,再在控制台执行webpack命令,会看到如下:

注意看红框部分,首先,title已经被修改了插件默认值;其次,id为app的div已经没有了。最后,可看到在body末尾插件帮我们把bundle.js插入。

template属性
看插件官网,插件有一个template属性,可以指定模板文件,插件能按照模板帮我们插入js或者css引用。

官网地址是:。

看官网描述,默认会有一个ejs的loader会解析模板,至于ejs是什么?ejs是一个模板语言,在nodejs开发中经常会用到,这里可以把ejs完全当做一个html格式来用。
所以,在src目录下,我们新建一个index.temp.ejs文件,并把public下的index.html的内容拷贝到该文件中,并修改至如下:

<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Webpack Example</title><body><div id="app" class="custom"></div></body></html>
Copy after login

可以看到,title已经被我们修改回webpack example了,并且也添加了id为app的div,还删除了script,接着,删除Public下的文件。然后我们再控制台输入webpack,等webpack打包编译完成,这时public下生成了bundle.js和index.html文件,编辑index.html文件,可以看到如下信息:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Webpack Example</title>
<link href="styles.css?1.1.11" rel="stylesheet"></head>
<body>
<div id="app" class="custom"></div>
<script type="text/javascript" src="bundle.js?1.1.11"></script></body>
</html>
Copy after login

在Body末尾,插件自动给我们把script加上了。

3.1.2 Extract-text-webpack插件

如果我们也想把css文件也自动插入,那么就会用到extract-text-webpack插件。

其官网地址是:。

官网的usage如下:

const ExtractTextPlugin = require("extract-text-webpack-plugin");

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ExtractTextPlugin.extract({
          fallback: "style-loader",
          use: "css-loader"
        })
      }
    ]
  },
  plugins: [
    new ExtractTextPlugin("styles.css?1.1.11"),
  ]
}
Copy after login

1.首先还是要先在控制台输入命令:

npm install extract-text-webpack-plugin --save-dev。
Copy after login

这里要注意:官网只提示安装extract插件,其实在编译的时候,还需要style-loader和css-loader,所以还要执行命令:

npm install style-loader --save-dev
Copy after login
npm install css-loader --save-dev
Copy after login

2.然后在webpack.config.js文件上面,require一下这个插件
3.按照官网的用法,编写module节点,最后如下所示:

var HtmlWebpackPlugin = require("html-webpack-plugin");
var ExtractTextWebpackPlugin = require("extract-text-webpack-plugin");
module.exports = {
    entry: __dirname + "/src/main.js?1.1.11",
    output: {
        path: __dirname + "/public",
        filename: "bundle.js?1.1.11"
    },
    module: {
        rules: [{
            test: /\.css$/,
            use: ExtractTextWebpackPlugin.extract({
                fallback: "style-loader",
                use: "css-loader"
            })
        }]
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: "./src/index.temp.ejs"
        }),
        new ExtractTextWebpackPlugin("styles.css?1.1.11")
    ]
}
Copy after login

注意

  • test是正则表达式,不是字符串!!!,没有引号

  • 在webpack2中,module下的loaders改为rules,后者拥有更多的功能

4.接着,我们在src目录下新建一个index.css文件,并编辑编写如下样式:

.custom{
    font-size: 18px;
    color: bisque;
    border: 1px moccasin solid;
    padding: 5px;
}
Copy after login

5.然后,编辑index.temp.ejs文件,在div标签加入class="custom",如下图红框处:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Webpack Example</title>
</head>
<body>
<div id="app" class="custom"></div>
</body>
</html>
Copy after login

6.编辑main.js文件,在其顶部Import刚才新建的index.css文件,如下图:

import Hello from "./hello";
import IndexStyle from "./index.css?1.1.11";

document.getElementById("app").appendChild(Hello());
Copy after login

7.最后,在控制台输入命令

webpack
Copy after login

编译完成后,可以看到public目录下生成了style.css文件,编辑index.html文件,可以看到在Head中引入了Style.css文件,如下图:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Webpack Example</title>
    <link href="styles.css?1.1.11" rel="stylesheet"></head>
<body>
<div id="app" class="custom"></div>
<script type="text/javascript" src="bundle.js?1.1.11"></script></body>
</html>
Copy after login

3.2 开发服务器 - Webpack-dev-server

在开发中,我们会不断的调试页面和参数,如果每次都是执行webpack命令未免太累了,所以这里介绍一个开发服务器webpack-dev-server,它提供一个易于部署的服务器环境,并且具有实时重载的功能。

更多的文档可以参考:。

要使用这个功能,首先还先执行npm的安装命令

npm install webpack-dev-server --save-dev,
Copy after login

执行完成后,编辑package.json文件,添加"start"代码如下:

"scripts": {
  "test": "echo \"Error: no test specified\" && exit 1",
  "start":"webpack-dev-server --progress"}
Copy after login

"--progress"参数可以查看当前执行进度,在控制台输入"npm start"控制台会打印日志信息,最后出现编译成功,代表服务启动完成,这时打开http://localhost:8080,可以看到index.html的内容,如下图:

这个时候,编辑hello.js,添加一些字符串如下:

export default function () {
    const hello = document.createElement("div");
    hello.textContent = "Hello Webpack!This is my example!"
    return  hello;
}
Copy after login

保存后,打开浏览器不用刷新,就可以看到我们新添加的"This is my example"。

The above is the detailed content of Environment construction method for developing SPA applications using Vue2.X and Webpack2.X. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use python+Flask to realize real-time update and display of logs on web pages How to use python+Flask to realize real-time update and display of logs on web pages May 17, 2023 am 11:07 AM

1. Log output to file using module: logging can generate a custom level log, and can output the log to a specified path. Log level: debug (debug log) = 5) {clearTimeout (time) // If all results obtained 10 consecutive times are empty Log clearing scheduled task}return}if(data.log_type==2){//If a new log is obtained for(i=0;i

How to use Nginx web server caddy How to use Nginx web server caddy May 30, 2023 pm 12:19 PM

Introduction to Caddy Caddy is a powerful and highly scalable web server that currently has 38K+ stars on Github. Caddy is written in Go language and can be used for static resource hosting and reverse proxy. Caddy has the following main features: Compared with the complex configuration of Nginx, its original Caddyfile configuration is very simple; it can dynamically modify the configuration through the AdminAPI it provides; it supports automated HTTPS configuration by default, and can automatically apply for HTTPS certificates and configure it; it can be expanded to data Tens of thousands of sites; can be executed anywhere with no additional dependencies; written in Go language, memory safety is more guaranteed. First of all, we install it directly in CentO

Real-time protection against face-blocking barrages on the web (based on machine learning) Real-time protection against face-blocking barrages on the web (based on machine learning) Jun 10, 2023 pm 01:03 PM

Face-blocking barrage means that a large number of barrages float by without blocking the person in the video, making it look like they are floating from behind the person. Machine learning has been popular for several years, but many people don’t know that these capabilities can also be run in browsers. This article introduces the practical optimization process in video barrages. At the end of the article, it lists some applicable scenarios for this solution, hoping to open it up. Some ideas. mediapipeDemo (https://google.github.io/mediapipe/) demonstrates the mainstream implementation principle of face-blocking barrage on-demand up upload. The server background calculation extracts the portrait area in the video screen, and converts it into svg storage while the client plays the video. Download svg from the server and combine it with barrage, portrait

How to configure nginx to ensure that the frps server and web share port 80 How to configure nginx to ensure that the frps server and web share port 80 Jun 03, 2023 am 08:19 AM

First of all, you will have a doubt, what is frp? Simply put, frp is an intranet penetration tool. After configuring the client, you can access the intranet through the server. Now my server has used nginx as the website, and there is only one port 80. So what should I do if the FRP server also wants to use port 80? After querying, this can be achieved by using nginx's reverse proxy. To add: frps is the server, frpc is the client. Step 1: Modify the nginx.conf configuration file in the server and add the following parameters to http{} in nginx.conf, server{listen80

Using Jetty7 for Web server processing in Java API development Using Jetty7 for Web server processing in Java API development Jun 18, 2023 am 10:42 AM

Using Jetty7 for Web Server Processing in JavaAPI Development With the development of the Internet, the Web server has become the core part of application development and is also the focus of many enterprises. In order to meet the growing business needs, many developers choose to use Jetty for web server development, and its flexibility and scalability are widely recognized. This article will introduce how to use Jetty7 in JavaAPI development for We

How to implement form validation for web applications using Golang How to implement form validation for web applications using Golang Jun 24, 2023 am 09:08 AM

Form validation is a very important link in web application development. It can check the validity of the data before submitting the form data to avoid security vulnerabilities and data errors in the application. Form validation for web applications can be easily implemented using Golang. This article will introduce how to use Golang to implement form validation for web applications. 1. Basic elements of form validation Before introducing how to implement form validation, we need to know what the basic elements of form validation are. Form elements: form elements are

How to enable administrative access from the cockpit web UI How to enable administrative access from the cockpit web UI Mar 20, 2024 pm 06:56 PM

Cockpit is a web-based graphical interface for Linux servers. It is mainly intended to make managing Linux servers easier for new/expert users. In this article, we will discuss Cockpit access modes and how to switch administrative access to Cockpit from CockpitWebUI. Content Topics: Cockpit Entry Modes Finding the Current Cockpit Access Mode Enable Administrative Access for Cockpit from CockpitWebUI Disabling Administrative Access for Cockpit from CockpitWebUI Conclusion Cockpit Entry Modes The cockpit has two access modes: Restricted Access: This is the default for the cockpit access mode. In this access mode you cannot access the web user from the cockpit

Is PHP front-end or back-end in web development? Is PHP front-end or back-end in web development? Mar 24, 2024 pm 02:18 PM

PHP belongs to the backend in web development. PHP is a server-side scripting language, mainly used to process server-side logic and generate dynamic web content. Compared with front-end technology, PHP is more used for back-end operations such as interacting with databases, processing user requests, and generating page content. Next, specific code examples will be used to illustrate the application of PHP in back-end development. First, let's look at a simple PHP code example for connecting to a database and querying data:

See all articles