在 Vite项目中使用插件 @rollup/plugin-inject 注入全局 jQuery的过程详解

写在前面

在一次项目脚手架升级的过程中,将之前基于 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-Vue3</title>
 <script src="/src/jquery.min.js"></script>
 </head>
 <body>
 <div id="app"></div>
 <script type="module" src="/src/main.js"></script>
 </body>
</html>

方法二、使用插件 @rollup/plugin-inject 注入 jquery

首先,安装 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.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 加载的模块在使用时将不再需要 importrequire 进行引入。
  • 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 解决模块之间引用问题

使用 @rollup/plugin-node-resolve 解决模块之间引用问题。

作者:Never Yu原文地址:https://blog.csdn.net/csdn_yudong/article/details/128122672

%s 个评论

要回复文章请先登录注册