在一次项目脚手架升级的过程中,将之前基于 webpack 搭建的项目移植到 Vite 构建。
一些组件库是依赖 jQuery 的,如:Bootstrap;引入这些组件的时候,需要项目中已经存在 jQuery 环境。
例如:当我们在 main.js 中使用如下方式引入 Bootstrap 时:
// main.js
/* bootstarp */
import '@/assets/css/bootstrap.min.css'
import '@/assets/js/bootstrap.min.js'
我们必须保证拥有全局的 jQuery 环境。否则,在 Bootstrap 中会报缺少 jQuery 的错误。
在原项目中,在 webpack.base.conf.js 中,有一段关于 jQuery 的配置是这样的:
module.exports = {
...
plugins: [
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
"windows.jQuery": "jquery"
})
],
...
}
使用 webpack.ProvidePlugin 插件全局注入 jQuery,这样在项目构建启动运行后,项目中就有了全局的 jQuery 环境。
那么,在 Vite 的项目中,该如何来配置或者来实现这个功能呢?
全局静态引入的意思,就是在项目的主页面文件 index.html 中,使用原始引入 js 文件的方式来引入 jquery。
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite-Vue3title>
<script src="/src/jquery.min.js">script>
head>
<body>
<div id="app">div>
<script type="module" src="/src/main.js">script>
body>
html>
首先,安装 jquery、@rollup/plugin-inject.
npm i jquery @rollup/plugin-inject -S
在项目的配置文件 vite.config.js 中:
import inject from '@rollup/plugin-inject'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
vue(),
inject({
$: "jquery", // 这里会自动载入 node_modules 中的 jquery
jQuery: "jquery",
"windows.jQuery": "jquery"
})
],
resolve: {
alias: {
'@': resolve(__dirname, './src')
}
}
})
这样,即可在 Vite 项目中实现 webpack.ProvidePlugin 的功能。
webpack 的插件使用方式:// webpack.base.conf.js
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
...
plugins: [
new webpack.ProvidePlugin({}),
new webpack.IgnorePlugin('/^\.\/locale$/, /moment$/'),
// or(或者)
new HtmlWebpackPlugin({
template: './src/index.html'
})
]
...
}
这里面有两种 webpack 的插件使用方式:new webpack.ProvidePlugin() 和 new HtmlWebpackPlugin();
前者是 webpack 内置的模块,后者不是 webpack 内置的模块,需要使用 npm 先进行安装再使用。
ProvidePlugin,是 webpack 的内置模块。ProvidePlugin 加载的模块在使用时将不再需要 import 和 require 进行引入。jquery 为例,用 ProvidePlugin 进行实例初始化后,jquery 就会被自动加载并导入对应的 node 模块中。new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery'
})
// 然后我们可以在代码中直接使用
$('#item'); // <= just works
jQuery('#item'); // <= just works
// $ is automatically set to the exports of module "jquery"
使用 @rollup/plugin-node-resolve 解决模块之间引用问题。
—————————— 【正文完】——————————
前端学习交流群,想进来面基的,可以加群: 832485817,685486827;

写在最后: 约定优于配置 —— 软件开发的简约原则
——————————【完】——————————
我的:
个人网站: https://neveryu.github.io/neveryu/
Github: https://github.com/Neveryu
微信: miracle421354532
更多学习资源请关注我的微信…好吗