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

巴扎黑
Release: 2017-07-22 15:40:30
Original
1234 people have browsed it

[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!

Related labels:
web
source:php.cn
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template