在 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'- 1
- 2
- 3
- 4
我们必须保证拥有全局的 jQuery 环境。否则,在 Bootstrap 中会报缺少 jQuery 的错误。
在原项目中,在 webpack.base.conf.js 中,有一段关于 jQuery 的配置是这样的:
module.exports = { ... plugins: [ new webpack.ProvidePlugin({ $: "jquery", jQuery: "jquery", "windows.jQuery": "jquery" }) ], ...}- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
使用 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>- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
方法二、使用插件 @rollup/plugin-inject 注入 jquery
首先,安装 jquery、@rollup/plugin-inject.
npm i jquery @rollup/plugin-inject -S- 1
在项目的配置文件 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') } }})- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
这样,即可在 Vite 项目中实现 webpack.ProvidePlugin 的功能。
课外知识:
一、关于 webpack.ProvidePlugin
- 了解
webpack的插件使用方式:
// webpack.base.conf.jsconst HtmlWebpackPlugin = require('html-webpack-plugin')module.exports = { ... plugins: [ new webpack.ProvidePlugin({}), new webpack.IgnorePlugin('/^\.\/locale$/, /moment$/'), // or(或者) new HtmlWebpackPlugin({ template: './src/index.html' }) ] ...}- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
这里面有两种 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 worksjQuery('#item'); // <= just works// $ is automatically set to the exports of module "jquery"- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
二、使用 @rollup/plugin-node-resolve 解决模块之间引用问题
使用 @rollup/plugin-node-resolve 解决模块之间引用问题。
——————————【正文完】——————————
前端学习交流群,想进来面基的,可以加群: ,;
写在最后: 约定优于配置 —— 软件开发的简约原则
——————————【完】——————————
我的:
个人网站:
Github:
微信: miracle421354532
更多学习资源请关注我的微信…好吗