2-6 (webapack4 loader) webpack文件处理(file-loader)之第三方js库处理

webpack第三方js库处理
以jquery库为例:
一.本地导入方式

1)下载jquery文件,进入官网https://jquery.com/.
在这里插入图片描述
点击上面的按钮后,会出现下面的页面:
在这里插入图片描述

production版本是精简和和压缩后的,为实际开发网站时使用,减小文件大小
developmet版本是原生js库,可以用于自己查看jquery源代码来学习jquery
根据你的需要点击下载,点击后会发现是一整页代码,你只要command+s(control+s)保存即可。

2)配置webpack.config.js文件
在webpack.config.js文件中的module.exports = {}下写入resolve和plugins:

resolve:{
		alias:{
			jQuery:path.resolve(__dirname,'public/js/jquery-3.5.1.min.js')
		}
	},
	plugins:[
		new webpack.ProvidePlugin({
			jQuery:"jQuery"
		})
	]

其中,webpack.ProvidePlugin的参数是键值对形式,键就是我们项目中使用的变量名,我们可以随意取名(上面的代码中,我就取名为jQuery);值就是键所指向的库(上面代码中,指向jQuery库)。
webpack.ProvidePlugin会先从npm安装包中查找是否有符合的库。
如果webpack配置了resolve.alias选项,那么webpack.ProvidePlugin就会顺着alias里面设置的路径一直找下去(上面代码中,我设置的路径为’public/js/jquery-3.5.1.min.js’)。

使用webpack.ProvidePlugin前,需要引入webpack,所以需要在webpack.config.js文件开头引入webpack,代码为:
const webpack = require('webpack');

全部webpack.config.js文件代码为:

const path = require('path');
const webpack = require('webpack');

module.exports = {
	entry:'./public/index.js',
	output:{
		path:path.resolve(__dirname,'build'),
		filename:'bundle.js'
	},
	devServer:{
		contentBase:'./build',
		host:'localhost',
		port:8080,
		open:true,
	},
	module:{
		rules:[
			{
				test:/\.css$/,
				use:['style-loader','css-loader']
			},
			{
				test:/\.scss$/,
				use:['style-loader','css-loader','sass-loader',{
					loader:'postcss-loader',
					options:{
						plugins:[
							require("autoprefixer")
						]
					}
				}]
			},
			{
				test:/\.(png|jpg|gif|jepg)$/,
				use:[{
					loader:'file-loader',
					options:{
						name:'[path]dudu.jpg',
					}
				}]
			},
			{
				test:/\.(eot|svg|ttf|woff|woff2)/,
				use:[{
					loader:'file-loader',
					options:{
						outputPath:'./fonts',
					}
				}]
			},
		]
	},
	resolve:{
		alias:{
			jQuery:path.resolve(__dirname,'public/js/jquery-3.5.1.min.js')
		}
	},
	plugins:[
		new webpack.ProvidePlugin({
			jQuery:"jQuery"
		})
	]
}

3)在index.js中引入jQuery,代码示例:
jQuery("#header").addClass('one');
4)在终端输入npm run dev进行打包
这时,打开index.html文件,检查元素,如下图所示:
在这里插入图片描述div中就出现了 class=“one”。

二.npm安装模块方式

1)打开终端,进入到项目文件夹路径,安装jquery库,代码为:
cnpm install jquery --save-dev
2)在index.js里引入

import $ from 'jquery'

此时是以$作为变量名,所以引用的时候代码为:

$("#header").addClass('one');

3)使用npm安装模块方式不需要配置resolve和plugins。
4)打开终端,进入到项目文件夹路径,输入npm run dev进行打包。
这时就会出现和本地导入方式一样的效果。

猜你喜欢

转载自blog.csdn.net/xt_123456/article/details/106094424