全局变量引入
jquery的引入
npm i jquery -S
let webpack = require('webpack')
new webpack.ProvidePlugin({
$: 'jquery'
})
其他情况
- 暴露全局
npm i expose-loader -D
暴露全局的loader
可以在js中 import $ from 'expose-loader?$!jquery'
// 全局暴露jquery为$符号
可以调用window.$
也可在webpack.config.js
中配置 rules
{
test: require.resolve('jquery'),
use: 'expose-loader?$'
}
以后在.js
文件中引入
import $ from 'jquery'
- 如何在每个模块中注入
let webpack = require('webpack')
// 在plugins中配置
new webpack.ProvidePlugin({
$: 'jquery'
})
- 在
index.html
中通过script
标签引入jquery
, 但是在js
中,用import
会重新打包jquery
,如何避免
从输出的bundle 中排除依赖
externals: {
jquery: 'jQuery'
}
此时在index.js上
import $ from 'jquery'
console.log($, 123456) // 可以正常运行