从零开始的webpack生活-0x006:providerPlugin全局定义
文章目录
0x001 概述
上一章讲的是definePlugin的用法,和这一章依旧没有任何关系,这一章讲的时候providerPlugin。
0x002 插件介绍
就是提供全局变量啦
0x003 全局定义jquery栗子
-
初始化项目
+ 0x006-provider-plugin + src - index.js - webpack.config.js -
安装依赖包
$ cnpm init -y $ cnpm install webpack --save-dev $ cnpm install jquery --save -
编写
webpack.config.jsvar path = require('path') module.exports = { entry : ['./src/index.js'], output : { path : path.resolve(__dirname, 'dist'), filename: 'index.js' } } -
添加插件,并定义
jQueryvar 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' }) ] } -
调用
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> - 打包并用浏览器打开
./src/index.html,查看控制台
0x004 全局定义自定义函数栗子
-
添加定义
timestamp: [path.resolve(__dirname, 'src/utils'), 'default'] -
添加文件
./src/utilsexport default function () { console.log(new Date().getTime()) } -
调用
// ./src/index.js timestamp() -
打包并执行
$ webpack $ node ./dist/index.js # 输出 1509977476685
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论