在?Vite項目中使用插件?@rollup/plugin-inject?注入全局?jQuery的過程詳解
寫在前面
在一次項目腳手架升級的過程中,將之前基于 webpack 搭建的項目移植到 Vite 構建。
一些組件庫是依賴 jQuery 的,如:Bootstrap;引入這些組件的時候,需要項目中已經存在 jQuery 環(huán)境。
例如:當我們在 main.js 中使用如下方式引入 Bootstrap 時:
// main.js /* bootstarp */ import '@/assets/css/bootstrap.min.css' import '@/assets/js/bootstrap.min.js'
我們必須保證擁有全局的 jQuery 環(huán)境。否則,在 Bootstrap 中會報缺少 jQuery 的錯誤。
在原項目中,在 webpack.base.conf.js 中,有一段關于 jQuery 的配置是這樣的:
module.exports = {
...
plugins: [
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
"windows.jQuery": "jquery"
})
],
...
}使用 webpack.ProvidePlugin 插件全局注入 jQuery,這樣在項目構建啟動運行后,項目中就有了全局的 jQuery 環(huán)境。
那么,在 Vite 的項目中,該如何來配置或者來實現這個功能呢?
方法一、全局靜態(tài)引入
全局靜態(tài)引入的意思,就是在項目的主頁面文件 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加載的模塊在使用時將不再需要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 解決模塊之間引用問題
使用 @rollup/plugin-node-resolve 解決模塊之間引用問題。
到此這篇關于在 Vite項目中,使用插件 @rollup/plugin-inject 注入全局 jQuery的文章就介紹到這了,更多相關@rollup/plugin-inject 注入全局 jQuery內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

