# [Vue] 使用 jQuery ###### tags: `Vue.js` `jQuery` ## 透過 npm 或 yarn 安裝 安裝 jQuery:`npm install jQuery` 或 `yarn add jquery` ### 使用 Vite 創建的 Vue 2、Vue 3 專案 #### 引入方法一:在 `main.js` `import` ```javascript import jQuery from 'jquery'; Object.assign(window, { $: jQuery, jQuery }); ``` #### 引入方法二:透過 Rollup plugin 1. 安裝:`npm install @rollup/plugin-inject --save-dev` 2. 在 `vite.config.js` 加上 ```javascript import inject from '@rollup/plugin-inject'; export default defineConfig({ plugins: [ inject({ $: 'jquery', jQuery: 'jquery', 'windows.jQuery': 'jquery', }), ], }); ``` ### 使用 Vue CLI 創建的 Vue 2、Vue 3 專案 #### 引入方法一:在 `main.js` `import` ```javascript import jQuery from 'jquery'; Object.assign(window, { $: jQuery, jQuery }); ``` #### 引入方法二:在 `main.js` `require` ```javascript Object.assign( window, { $: require('jquery'), jQuery: require('jquery'), }, ); ``` #### 引入方法三:在 `vue.config.js` 加上 ```javascript= const webpack = require('webpack'); // module.exports = { module.exports = defineConfig({ configureWebpack: { plugins: [ new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery', 'windows.jQuery': 'jquery', }), ], }, }); // }; ``` ## 透過 CDN 引入 使用 Vue CLI、Vite 創建的 Vue 2、Vue 3 專案寫法皆一樣,在 `index.html` 加上 ```htmlembedded <script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script> ``` ## 若有使用 ESLint,不想出現 `no-undef` :::info [ESLint 官方文件:Using configuration files](https://eslint.org/docs/latest/use/configure/language-options#using-configuration-files-1 "Configure Language Options - ESLint - Pluggable JavaScript Linter") ::: ```javascript= // .eslintrc.js module.exports = { // 定義需要的 global variables globals: { $: 'readonly', // jQuery,避免出現 '$' is not defined jQuery: 'readonly', // jQuery,避免出現 'jQuery' is not defined }, }; ``` --- :::info 建立日期:2021-02-12 更新日期:2024-03-10 :::