webpack基础入门

webpack介绍

webpack:是一个前端资源的打包工具,它可以将js、image、css等资源当成一个模块进行打包。

###webpack的优点:

  • 模块化开发
  • 编译typescript、ES6等高级语法
  • CSS预编译

###webpack的缺点:

  • 配置繁琐,文档不丰富

webpack的安装

  • 安装node.js

  • 安装npm
    npm:Node Package Manage,node包管理和分发的工具,可以对应用的依赖进行管理,类似Maven工具。可以通过npm方便地下载js库,打包js文件。
    node.js已集成了npm工具,可通过npm -v 查看当前版本。

    • 查看配置信息:

      npm config ls
      

      运行结果:

      metrics-registry = "https://registry.npmjs.org/"
      scope = ""
      user-agent = "npm/6.4.1 node/v10.14.2 win32 x64"
      
      ; userconfig C:\Users\yang.zhongming\.npmrc
      prefix = "C:\\Users\\Administrator\\AppData
      
      ; node bin location = D:\Program Files\nodejs\node.exe
      cwd = C:\Users\Administrator
      HOME = C:\Users\Administrator
      "npm config ls -l" to show all defaults.
      
    • 设置包路径:
      默认的包管理路径:

      C:\Users\Administrator\AppData\Roaming\npm\node_modules
      

      修改包路径:
      在node.js的安装目录下创建npm_modules和npm_cache

      -- 设置路径
      npm config set prefix "D:\Program Files\nodejs\npm_modules"
      npm config set cache "D:\Program Files\nodejs\npm_cache"
      
      -- 查看路径
      npm config ls
      
      ; cli configs
      metrics-registry = "https://registry.npmjs.org/"
      scope = ""
      user-agent = "npm/6.4.1 node/v10.14.2 win32 x64"
      
      ; userconfig C:\Users\Administrator\.npmrc
      cache = "D:\\Program Files\\nodejs\\npm_cache"
      prefix = "D:\\Program Files\\nodejs\\npm_modules"
      
      ; builtin config undefined
      
      ; node bin location = D:\Program Files\nodejs\node.exe
      ; cwd = D:\Program Files\nodejs
      ; HOME = C:\Users\Administrator
      ; "npm config ls -l" to show all defaults.
      
  • 安装cnpm
    国内镜像,通常使用淘宝镜像来安装cnpm

    npm install -g cnpm --registry=https://registry.npm.taobao.org
    -- 查看安装版本
    cnpm -v 
    -- 版本信息
    cnpm@6.0.0 (D:\Program Files\nodejs\npm_modules\node_modules\cnpm\lib\parse_argv.js)
    npm@6.9.0 (D:\Program Files\nodejs\npm_modules\node_modules\cnpm\node_modules\npm\lib\npm.js)
    node@10.14.2 (D:\Program Files\nodejs\node.exe)
    npminstall@3.20.2 (D:\Program Files\nodejs\npm_modules\node_modules\cnpm\node_modules\npminstall\lib\index.js)
    prefix=D:\Program Files\nodejs\npm_modules
    win32 x64 6.1.7601
    registry=https://registry.npm.taobao.org
    
  • 安装nrm

  • 安装webpack
    webpack安装分为本地安装和全局安装,本地安装是将webpack安装在当前项目的node_modules目录中,仅对当前项目有效。全局安装类似系统安装,对所有项目有效。

    • 本地安装:

      cd 工程目录
      npm install --save webpack
      npm install --save-dev webpack-cli((4.0以后的版本需要安装webpack-cli)
      
    • 全局安装
      webpack的js包下载到npm的包路径下

      npm install webpack -g
      
    • 指定版本安装

      cnpm install --save-dev webpack@3.6.0
      
    • 安装执行以下命令,确认是否安装成功

      webpack
      

      出现以下信息证明安装成功:

      No configuration file found and no output filename configured via CLI option.
      A configuration file could be named 'webpack.config.js' in the current directory.
      Use --help to display the CLI options.
      

webpack的打包

分模块开发:

<!DOCTYPE html>
<html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>vue.js 入门程序</title>
    <script src="./js/vue.min.js"></script>
</head>
<body>
    <div id="app">
        <a v-bind:href="url"><span v-text="name"></span></a>
        <input type="text" v-model="num1"> +
        <input type="text" v-model="num2"> =
        <span v-text="result"></span>
        <button v-on:click="change">计算</button>
    </div>
</body>
<script type="text/javascript">
    var vm = new Vue({
        el:"#app",
        data:{name:"计算器",
              num1:0,
              num2:0,
              result:0,
              url:'http://www.baidu.com'
        },
        methods:{
            change:function () {
                this.result = Number.parseInt(this.num1) + Number.parseInt(this.num2)
                alert(this.result)
            }
        }
    });
</script>
</html>

对上述源代码进行分模块开发:

  • 模块model.js的创建:

    //子模块使用的方法
    var add = function (x,y){
      return  x + y;
    }
    //导出方法,module固定关键字
    module.exports.add = add;
    
    //多个方法导出参考如下写法:
    module.exports  = {add1,add2};
    
  • 主程序main.js的创建:

    var {add} = require("./model01.js");
    var Vue = require("./vue.min.js");
    
    var VM = new Vue({
        el:'#app',
        data:{
        name:'yzhm',
        num1:0,
        num2:1,
        url:'http://www.baidu.com',
    },
    methods:{
        change:function() {
        this.result = add(Number.parseInt(this.num1),Number.parseInt(this.num2))
        }
        }
    });
    
  • webpack打包:

    cd js文件夹
    webpack main.js build.js
    

    执行后显示如下:
    D4r3M.png

    原因是webpack版本过高,打包命令修改为:

    webpack main.js -o build.js
    

    D43IU.png

  • 修改主画面:

    <!DOCTYPE html>
    <html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml">
    <head>
       <meta charset="UTF-8">
       <title>vue.js 入门程序</title>
       <script src="./js/build.js">
       </script>
      </head>
    <body>
    <div id="app">
    <a v-bind:href="url"><span v-text="name"></span></a>
    <input type="text" v-model="num1"> +
    <input type="text" v-model="num2"> =
    <span v-text="result"></span>
    <button v-on:click="change">计算</button>
    </div>
    </body>
    </html>
    
    --注:主画面中引用的如下代码,应放在</body></html>之间,否则可能会出现引用无效的情况。
    <script src="./js/build.js">
    

webpack-dev-server介绍

webpack-dev-server开发服务器,它的功能可以实现热加载 并且自动刷新浏览器。

webpack的安装

npm install webpack@3.6.0 webpack-dev-server@2.9.1 html-webpack-plugin@2.30.1 --save-dev

安装完成,会发现程序目录出现一个package.json文件,此文件中记录了程序的依赖。

{
"scripts": {
"dev": "webpack-dev-server --inline --hot --open --port 5008"
},
"devDependencies": {
"html-webpack-plugin": "^2.30.1",
"webpack": "^3.6.0",
"webpack-dev-server": "^2.9.1"
}
}

参数说明:

--inline:自动刷新
--hot:热加载
--port:指定端口
--open:自动在默认浏览器打开
--host:可以指定服务器的 ip,不指定则为127.0.0.1,如果对外发布则填写公网ip地址
devDependencies:开发人员在开发过程中所需要的依赖。
scripts:可执行的命令

###配置webpack.config.js
webpack.config.js是webpack的配置文件。在此文件中可以配置应用的入口文件、输出配置、插件等,其中要实现热加载自动刷新功能需要配置html-webpack-plugin插件。

html-webpack-plugin的作用是根据html模板在内存生成html文件,它的工作原理是根据模板文件在内存中生成一个index.html文件

  • 配置模板文件:

     <!DOCTYPE html>
     <html lang="en">
     <head>
     <meta charset="UTF-8">
     <title>vue.js常用指令的测试</title>
     </head>
     <body>
     <!--实现在body区域显示一个传智播客名称-->
     <div id="app">
     <!--相当于MVVM的view视图-->
     <!--{{name}}-->
     <a v-bind:href="url">
     <span v-text="name"></span>
     </a>
     <input type="text" v-model="num1"/> +
     <input type="text" v-model="num2"/>=
     <!-- <span v-text="Number.parseInt(num1)+Number.parseInt(num2)"></span>-->
     <span v-text="result"></span>
     <!--{{Number.parseInt(num1)+Number.parseInt(num2)}}-->
     <button v-on:click="change">计算</button>
     </div>
    </body>
    </html>
    
    以上代码已去掉引入的script标签,即引入的build.js
    
  • 配置 html-webpack-plugin,在webpack.config.js中配置html-webpack-plugin插件:

    //引用html-webpack-plugin插件,作用是根据html模板在内存生成html文件,它的工作原理是根据模板文件在内存中生成一个index.html文件。
    var htmlwp = require('html-webpack-plugin');
    module.exports={
    entry:'./src/main.js',  //指定打包的入口文件
    output:{
        path : __dirname+'/dist',  // 注意:__dirname表示webpack.config.js所在目录的绝对路径
        filename:'build.js'           //输出文件
    },
    devtool: 'eval-source-map',
    plugins:[
        new htmlwp({
            title: '首页',  //生成的页面标题<head><title>首页</title></head>
            filename: 'index.html', //webpack-dev-server在内存中生成的文件名称,自动将build注入到这个页面底部,才能实现自动刷新功能
            template: 'vue_02.html' //根据vue_02.html这个模板来生成(这个文件请程序员自己生成)
        })
    ]
    

    }

  • 启动

    • 使用webstorm,右键package.json文件,选择“Show npm Scripts”
    • 双击dev,自动打开浏览器
  • debug调试

    • 在webpack.config.js中配置,参照上述完整配置:

      devtool: 'eval-source-map'
      
    • 在add方法中添加debugger,例如:

      // 定义add函数
      function add(x, y) {
      debugger
      return x + y }
      
0%