# 十.全局变量引入

jquery 引入的几种方式(在处理 js 语法的基础上改)

  • 1) expose-loader 暴露到 window 上
  • 2)providePlugin 给每个模块提供一个$
  • 3)引入不打包

# 1.安装

cnpm i jquery -S
1
cnpm i expose-loader -D
1

# 2.文件

src/index.js 添加

import $ from "expose-loader?$!jquery";
console.log($);
console.log(window.$);
1
2
3
import $ from "jquery";
console.log($);
console.log(window.$);
1
2
3

# 3.配置

webpack.config.js

···
{
    test: require.resolve("jquery"),
    use: "expose-loader?$!jquery"
},
···
1
2
3
4
5
6

# 4.运行

npm run dev
1

可以看到控制台中 window.$不是 undefined

# 5.为每个模块提供一个$

webpack.config.js

···
let webpack = require("webpack");
···
new webpack.ProvidePlugin({
    $: "jquery" //在每个模块中注入$
})
···
// {
//   test: require.resolve("jquery"),
//   use: "expose-loader?$!jquery"
// },
···
1
2
3
4
5
6
7
8
9
10
11
12

修改 src/index.js 文件

// import $ from "expose-loader?$!jquery";
import $ from "jquery";
//expose-loader 暴露 全局的loader 内联的loader
//pre 前面执行的loader normal 普通的loader 内联loader 后置
console.log($);
console.log(window.$);
1
2
3
4
5
6

运行

npm run dev
1

可以看到 window.$不是 undefined

# 6.引入不打包

index.html 中加入

<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
1

wenbpack.config.js 中

···
// new webpack.ProvidePlugin({
//   $: "jquery" //在每个模块中注入$
// })
···
externals: [{ jquery: "$" }],
···
1
2
3
4
5
6
7

打包

npm run build
1

可以看到 jquery 没有被打包

完整代码 (opens new window)