webpack+gulp实现自动构建部署

来源:互联网 发布:大数据是一种思维方式 编辑:程序博客网 时间:2024/06/05 07:12

1、初始化webpack

npm init

2、用npm 安装webpack

npm install webpack -g

此时 Webpack 已经安装到了全局环境下,可以通过命令行 webpack -h 查看相关指令

3、进入项目目录、确定已有package.json,前面已经初始化了,所以会有一个package.json的文件,没有就npm init创建

4、把webpack加载到package.json文件里

npm install webpack --save-dev

5、查看webpack 版本信息

npm info webpack

6、如果要使用webpack开发工具,要单独安装 webpack-dev-server

webpack-dev-server是一个小型的node.js Express服务器,它使用webpack-dev-middleware中间件来为通过webpack打包生成的资源文件提供Web服务。它还有一个通过Socket.IO连接着webpack-dev-server服务器的小型运行时程序。webpack-dev-server发送关于编译状态的消息到客户端,客户端根据消息作出响应。

npm install webpack-dev-server --save-dev

7、webpack-dev-server有两种模式支持自动刷新——iframe模式和inline模式

iframe模式

1、在iframe模式下:页面是嵌套在一个iframe下的,在代码发生改动的时候,这个iframe会重新加载使用iframe模式,无需额外配置,只需在浏览器输入:http://localhost:8080/webpack-dev-server/index.html

inline模式

2、在inline模式下:一个小型的webpack-dev-server客户端会作为入口文件打包,这个客户端会在后端代码改变的时候刷新页面使用inline模式有两种方式:命令行和nodejs API    1)命令行: 在运行时,加上 --inline 选项    2)webpack-dev-server --inline

8、webpack配置

webpack是需要进行配置的,我们在使用webpack的时候,会默认 webpack.config.js 为我们的配置文件。所以接下来,我们新建这个js文件。

webpack.config.js

var path = require("path");module.exports={    entry:{        admin:"./admin/index.js",//打包引入的文件        consumer:"./consumer/index.js"    },    output:{        path:path.join(__dirname,"dist"),////打包输出的路径        publicPath:"/dist/",//html引用路径,在这里是本地地址。        filename:"[name].longzhoufeng.js"//打包后的名字name是对应上面js的key,对应admin,consumer相关的名字    }};

9、package.json的文档需要加入

"start": "webpack-dev-server --progress --colors --port 8889 --hot --inline"
{  "name": "longzhoufeng",  "version": "1.0.1",  "description": "longzhoufeng webpack",  "main": "index.js",  "scripts": {    "test": "echo \"Error: no test specified\" && exit 1",    "start": "webpack-dev-server --progress --colors --port 8889 --hot --inline"  },  "author": "longzhoufeng",  "license": "ISC",  "devDependencies": {    "webpack": "^2.5.1",    "webpack-dev-server": "^2.4.5"  }}

10、我们在项目目录下,创建二个目录:admin目录、consumer目录

admin目录下创建二个文件:

index.html

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>this is admin page</title></head><body><h1>Admin</h1><p id="content"></p><script src="/dist/admin.longzhoufeng.js"></script></body></html>

index.js文件

document.getElementById("content").innerText="this is admin page"

11、consumer目录下创建二个文件:

index.html

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>this is consumer page</title></head><body><h1>Consumer</h1><p id="content"></p><script src="/dist/consumer.longzhoufeng.js"></script></body></html>

index.js文件

document.getElementById("content").innerText="this is consumer page!!!"

12、开始运行打包,在命令行下输入:

webpack

13、打包好了之后,我们再运行一下:start

npm start

在地址栏里输入:http://localhost:8889/admin/
就可以运行打包后文件了