从零开始的webpack生活-0x006:providerPlugin全局定义

0x001 概述

上一章讲的是definePlugin的用法,和这一章依旧没有任何关系,这一章讲的时候providerPlugin

0x002 插件介绍

就是提供全局变量啦

0x003 全局定义jquery栗子

  1. 初始化项目

    + 0x006-provider-plugin
      + src
        - index.js
      - webpack.config.js
  2. 安装依赖包

    $ cnpm init -y
    $ cnpm install webpack --save-dev
    $ cnpm install jquery --save
  3. 编写webpack.config.js

    var path       = require('path')
    module.exports = {
        entry  : ['./src/index.js'],
        output : {
            path    : path.resolve(__dirname, 'dist'),
            filename: 'index.js'
        }
    }
    
  4. 添加插件,并定义jQuery

    var path       = require('path')
    var webpack    = require('webpack')
    module.exports = {
        entry  : ['./src/index.js'],
        output : {
            path    : path.resolve(__dirname, 'dist'),
            filename: 'index.js'
        },
        plugins: [
            new webpack.ProvidePlugin({
                $     : 'jquery',
                jQuery: 'jquery'
            })
        ]
    }
  5. 调用jquery

    // ./src/index.js
    $(document).ready(function () {
        console.log($('#name')[0].innerHTML)
    })
    // ./src/index.html
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>providerPlugin</title>
    
    </head>
    <body>
    <p id="name">followWinter</p>
    </body>
    <script src="./../dist/index.js"></script>
    </html>
  6. 打包并用浏览器打开./src/index.html,查看控制台

    clipboard.png

0x004 全局定义自定义函数栗子

  1. 添加定义

    timestamp: [path.resolve(__dirname, 'src/utils'), 'default']
    
  2. 添加文件./src/utils

    export default function () {
        console.log(new Date().getTime())
    }
  3. 调用

    // ./src/index.js
    timestamp()
  4. 打包并执行

    $ webpack
    $ node ./dist/index.js
    # 输出
    1509977476685

0x005 资源

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值