shimming
低版本浏览器不支持promise,使用polyfill去实现promise就是一个垫片
jquery
- 新建jquery.ui.js
export function ui() {
$('body').css('background','red')
}
- 修改index.js,在其中使用jquery.ui.js
import _ from 'lodash'
import $ from 'jquery'
import { ui } from './jquery.ui'
ui()
const dom = $('<div>')
dom.html(_.join(['a','b','c'],'--!-'))
$('body').append(dom)
- 此时运行会报错,因为jquery.ui.js中并没有引入jquery,webpack基于模块打包,jquery.ui.js是无法找到$的(变量隔离)所以无法识别$
![](https://img.haomeiwen.com/i5118914/527a9dc694522776.png)
- 使用webpack的插件
plugins: [
new HtmlWebpackPlugin({
template: 'src/index.html'
}),
new CleanWebpackPlugin({
root: path.resolve(__dirname, '../')
}),
new webpack.ProvidePlugin({
// 模块中使用了$就自动引入jquery,并将jquery赋值给$
$: 'jquery'
})
]
-
此时
index.js
和jquery.ui.js
都不需要import $ from 'jquery'
,但是能成功运行,这种方式就叫垫片Shimming -
lodash也使用垫片,这样使用lodash的地方也不需要
import _ from 'lodash'
plugins: [
new HtmlWebpackPlugin({
template: 'src/index.html'
}),
new CleanWebpackPlugin({
root: path.resolve(__dirname, '../')
}),
new webpack.ProvidePlugin({
$: 'jquery',
_: 'lodash'
})
]
- 也可以为方法使用垫片
plugins: [
new HtmlWebpackPlugin({
template: 'src/index.html'
}),
new CleanWebpackPlugin({
root: path.resolve(__dirname, '../')
}),
new webpack.ProvidePlugin({
$: 'jquery',
_join: ['lodash','join']
})
]
// 此时jquery.ui.js可改写为
export function ui() {
$('body').css('background',_join(['green'],''))
}
修改this指向的垫片
- this是指向模块而非window的
console.log(this)
console.log(this === window)
![](https://img.haomeiwen.com/i5118914/a2bf1bd0d95ff59f.png)
- 使用
imports-loader
改变this指向
npm install imports-loader --save
module: {
rules: [{
test: /\.(jpg|png|gif)$/,
use: {
loader: "url-loader",
options: {
name: '[name]_[hash].[ext]',
outputPath: 'images/',
limit: 2048
}
}
},{
test: /\.js$/,
exclude: /node_modules/,
use: [{
loader: "babel-loader"
},{
// 使this指向window
loader: "imports-loader?this=>window"
}],
}]
}
![](https://img.haomeiwen.com/i5118914/f78e6be2e77c1969.png)
网友评论