美文网首页我爱编程
webpack的介绍以及应用

webpack的介绍以及应用

作者: 十年之后_b94a | 来源:发表于2018-02-08 09:44 被阅读0次

1) 什么是Webpack

视频教程
WebPack可以看做是模块打包机:它做的事情是,分析你的项目结构,找到JavaScript模块以及其它的一些浏览器不能直接运行的拓展语言(Scss,TypeScript等),并将其转换和打包为合适的格式供浏览器使用。

2) 安装

Webpack可以使用npm安装,新建一个空的练习文件夹(test),在终端中转到该文件夹后执行下述指令就可以完成安装。

初始化项目

npm init
//全局安装
npm install -g webpack
//安装到你的项目目录
npm install --save-dev webpack

创建index.js

//index.js
module.exports = function(str){
    alert(str);
}

在创建一个main.js

//main.js 引用了indexjs文件
require('./index.js')('hello webpack!!');
function word(){
  alert('webpack的初步使用!!')
}

在我们终端命令执行

webpack main.js main.bundle.js
image.png

执行结束后我们可以看到目录下多了main.bundle.js文件
此时我们打开此文件

/******/ (function(modules) { // webpackBootstrap
/******/    // The module cache
/******/    var installedModules = {};
/******/
/******/    // The require function
/******/    function __webpack_require__(moduleId) {
/******/
/******/        // Check if module is in cache
/******/        if(installedModules[moduleId]) {
/******/            return installedModules[moduleId].exports;
/******/        }
/******/        // Create a new module (and put it into the cache)
/******/        var module = installedModules[moduleId] = {
/******/            i: moduleId,
/******/            l: false,
/******/            exports: {}
/******/        };
/******/
/******/        // Execute the module function
/******/        modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/        // Flag the module as loaded
/******/        module.l = true;
/******/
/******/        // Return the exports of the module
/******/        return module.exports;
/******/    }
/******/
/******/
/******/    // expose the modules object (__webpack_modules__)
/******/    __webpack_require__.m = modules;
/******/
/******/    // expose the module cache
/******/    __webpack_require__.c = installedModules;
/******/
/******/    // define getter function for harmony exports
/******/    __webpack_require__.d = function(exports, name, getter) {
/******/        if(!__webpack_require__.o(exports, name)) {
/******/            Object.defineProperty(exports, name, {
/******/                configurable: false,
/******/                enumerable: true,
/******/                get: getter
/******/            });
/******/        }
/******/    };
/******/
/******/    // getDefaultExport function for compatibility with non-harmony modules
/******/    __webpack_require__.n = function(module) {
/******/        var getter = module && module.__esModule ?
/******/            function getDefault() { return module['default']; } :
/******/            function getModuleExports() { return module; };
/******/        __webpack_require__.d(getter, 'a', getter);
/******/        return getter;
/******/    };
/******/
/******/    // Object.prototype.hasOwnProperty.call
/******/    __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/    // __webpack_public_path__
/******/    __webpack_require__.p = "";
/******/
/******/    // Load entry module and return exports
/******/    return __webpack_require__(__webpack_require__.s = 0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
//这里就是我们写的函数了
_webpack_require__(1)('hello webpack');
function webpakck(){
    alert('webpakck初步使用!')
}

/***/ }),
/* 1 */
/***/ (function(module, exports) {

module.exports = function(str){
    alert(str);
}


/***/ })
/******/ ]);

而当我们每次修改index.js和main.js 都要在终端执行webpack命令重新编译

那么第一次打包的时候可以加上 --watch参数 这样就可以不用每次都要编译

webpack main.js main.bundle.js --watch

当然此时你不能退出终端命令

1-1)我们在js中引入css文件 -loader

//style.css
html,body{
  margin:0;
  padding:0;
}
body{
  background:red;
}

打包css文件需要安装其他的模块
cnpm i css-loader style-loader --save-dev;

//main.js
require('style-loader!css-loader!./style.css');  这里引入这两个模块  当然也可以不引用 在命令行执行打包的时候 带上命令参数
function say(str){
  alert('str')
}
say('你好!')

终端执行命令
webpack main.js mainNew.js
我们在index.html引入打包之后的文件mainNew.js
就可以看到css代码执行了

那么这次不在require()的时候引入loader在命令终端执行
webpack main.js mainNew.js --module-bind "css=style-loader!css-loader"
使用--module-bind 绑定参数

2)我们此时一个完整的项目目录

image.png

准备工作下载webpack 初始化package.json
注意创建webpack.config.js

//webpack.config.js
module.exports = {
  entry:'./src/script/main.js', //打包的入口文件
  output:{
      path:__dirname+'dist/js',   //打包的出口路径
      filename:'bundle.js'    //打包后的文件名
  }
}

这里的entry是入口文件,但是当一个网页运用多个js而且互相不引用(require)

entry:{main:'./src/script/main.js',a;'./src/script/a.js'}

那么相应的输出output 就要改变 因为会被覆盖掉

output:{
      path:__dirname+'dist/js',   //打包的出口路径
      filename:'[name].js'    //此时打包后的文件名是entry的key
  }

3自动把打包的js生成到html页面上

自动生成html页面上
1 自动引入.js文件,安装html-webpack-plugin插件
npm install html-webpack-plugin --save-dev
2 配置文件 webpack.config.js
var htmlWebpackPlugin = require('html-webpack-plugin');//引用插件
module.exports = {plugins:[
    new htmlWebpackPlugin()// 初始化插件
]}
3 目前dist/js目录下生成的.html文件与我们项目创建的index.html毫无关联,为了自动生成项目创建的index.html,设置plugins
plugins: [
    new htmlWebpackPlugin({
        filename:'index-[hash].html',//指定文件名字
        template: 'index.html',//指定dist/js下生成项目创建的index.html
        inject:'head'//指定.js文件打包后放置的位置
    })
4 指定.html文件在dist目录下,.js文件在dist/js目录下
output:{
        path:__dirname+'/dist',
        filename:'js/[name]-[chunkhash].js'
}

4)打包html代码

根据上文引用html-webpack-plugin插件

在配置plugins中可以传参数

//webpack.config.js
var htmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
  entry : {
    main:__dirname+'/src/script/main.js',  //入口文件地址
    a:__dirname+'/src/script/a.js',
  },
  output:{
    filename:'js/[name].js',  //输出的名字 [name]根据entry的key取值
    path:__dirname+'/dist',
    publicPath;'www.test.com//'  //在index.html嵌入打包后的js 地址会自动加上这个www.test.com//
  },
  plugins:[
    new htmlWebpackPlugin({
      filename:'index.html',  //输出的名字
      template:'index.html',  //模板地址
      inject:'head',  //在头部插入模块
      title:'初学webpack',  //自定义传参 在模板中怎么拿到这个值
      minify:{   //minify这个是配置打包html
        removeComments:true,  //删除注释
        collapseWhitespace:true//去除空格和回车
      }
    })
 ]
}

获取值和ejs的语法一样

//模板index.html 
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title><%= htmlWebpackPlugin.options.title %></title><!--获取刚刚的title的值-->
</head>
<body>
    <ul>
        <% for(var key in htmlWebpackPlugin.options){%>
            <li><%= key %></li>
        <%}%>
    </ul>
    <hr>
    <ul>
        <% for(var key in htmlWebpackPlugin.options){%>
            <li><%= JSON.stringify(htmlWebpackPlugin.options[key]) %></li>
        <%}%>
    </ul>
</body>
</html>

5)loader 官网

前文在1-1已经提到 在webpack处理特定的文件是需要loader配置的
例如:
1、css文件需要用到 css-loader和style-loader这两个模块
2、js文件如果有es6的语法浏览器是不能直接解析的即使使用webpack也不能解析这时需要babel-loader这个模块 babel官网
3、jade文件 就需要用到jade-loader模块
···
loder的使用
先下载你需要编译的文件的loader模块

cnpm i css-loader style-loader --save-dev  安装到你的项目目录下

使用的方法有三种
1、终端命令

webpack --module-bind jade-loader --module-bind 'css=style-loader!css-loader'

2、直接在文件中引用

require('style-loader!css-loader!style/style.css')

3、在配置文件中使用重点

//webpack.config.js
var htmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
  entry : {
    main:__dirname+'/src/script/main.js',  //入口文件地址
    a:__dirname+'/src/script/a.js',
  },
  output:{
    filename:'js/[name].js',  //输出的名字 [name]根据entry的key取值
    path:__dirname+'/dist',
    publicPath;'www.test.com//'  //在index.html嵌入打包后的js 地址会自动加上这个www.test.com//
  },
  module:{  //loader的使用
    rules:[{
      test:/\.css$/,  //正则匹配css文件
       use:[  //使用css-loader和style-loader这两个模块
          {loader:'style-loader'},
          {loader:'css-loader'}
        ]
    },
    {
      test;/\.jade$/  //匹配jade文件
      use:'jade-loader' //使用jade-loader这个模块
      }
    ]
  },
  plugins:[
    new htmlWebpackPlugin({
      filename:'index.html',  //输出的名字
      template:'index.html',  //模板地址
      inject:'head',  //在头部插入模块
      title:'初学webpack',  //自定义传参 在模板中怎么拿到这个值
      minify:{   //minify这个是配置打包html
        removeComments:true,  //删除注释
        collapseWhitespace:true//去除空格和回车
      }
    })
  ]
}

在配置文件中是可以传参的

配置Stylus

cnpm i stylus stylus-loader -D

module: {
        rules: [
            { test: /\.js$/, exclude: /node_modules/, loader: "babel-loader" },
            {test: /\.css$/, use: [ 'style-loader', 'css-loader']},
            {
                test: /\.styl$/, // 匹配对应.styl后缀的文件
                loader: ['style-loader', 'css-loader', 'stylus-loader'] // 使用那些loader来处理这个文件
            }
        ]
    },

5-1)重点压缩ES6文件
1、模块的安装 babel官网

npm install --save-dev babel-loader babel-core

2、代码的编写

module:{
    rules:[
         {test: /\.js$/, loader: 'babel-loader', options: {'presets': ['env']}}
    ]
}
或者
module:{
    rules:[
         {test: /\.js$/, use:[{loader:'babel-loader',options:{'presets':'env'}}]}
    ]
}

3、安装模块

npm install babel-preset-env --save-dev

4、创建.babelrc文件

//.babelrc
{
  "presets": ["env"]
}

5-2-1)压缩css文件
1、模块的安装

npm install --save-dev css-loader style-loader

2、代码的编写

module:{
  rules:[
      {test: /\.css$/, use: [ 'style-loader', 'css-loader' ]}
    ]
}

如果压缩css文件想要自动加上浏览器前缀以及一些其他的功能 可以
npm官网 查看postcss-loader 这里不做详细介绍
5-2-2)处理less/sass文件
1、模块的依赖

style-loader css-loader less-loader

2、代码的编写

module:{
  rules:[
      {test: /\.css$/, use: [ 'style-loader', 'css-loader' ,'less-loader']}
    ]
}

5-3)处理图片
1、应用场景
例如在项目中 在html文字中img src 一张图片 或者在css 使用背景图片 都是可以直接处理的
2、模块

cnpm i file-loader --save-dev

3、代码

module:{
  rules:[
      {test:/\.(jpg|png|gif)$/i,loader:'file-loader'}
  ]
}

6)优化处理速度

例如 我们在处理js文件的时候 用babel-loader

module:[
 {test:/\.js$/,loader:'babel-loader'}
]

可以发现其实处理速度在4000+ms以上 这是因为默认处理整个项目的所有js文件,但是往往开发中我们是不需要处理 node_modules文件中的js文件
所以我们可以增加参数

//webpack.config.js
const path = require('path');
module:[
  {test:/\.js$/,exclude:path.resolve(__dirname,'node_module'),loader:'babel-loader'}
]
或者
module:[
  {test:/\.js$/,include:path.resolve(__dirname,'src'),loader:'babel-loader'}
]

exclude的参数时排除哪个文件夹不处理
include的参数 是指定哪个文件夹需要babel处理

相关文章

网友评论

    本文标题:webpack的介绍以及应用

    本文链接:https://www.haomeiwen.com/subject/sirezxtx.html