shimming
低版本瀏覽器不支持promise服傍,使用polyfill去實現(xiàn)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是無法找到$的(變量隔離)所以無法識別$
- 使用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'
,但是能成功運行,這種方式就叫墊片Shimminglodash也使用墊片,這樣使用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)
- 使用
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"
}],
}]
}