ProvidePlugin:(官方文档解释)

自动加载模块,而不必在任何地方 import或 require它们。
理解:在项目中,存在业务逻辑相同的功能,为了减少代码的书写,我们一般会选择抽离出复用的代码写在一个**.js文件中,然后将其向外暴露出去;使用的时候通过import**导入。
假如项目中有 50+ 个单文件组件(.vue)且每个组件中都要使用这个模块(.js )中向外暴露的方法,那我们是不是需要 50+ 个import 语句。为了避免这种情况的发生,所以想到把该方法变成全局的。把某个方法变成全局方法有多种方式,此文章仅记录通过webpack.ProvidePlugin进行挂载!!!
先附上官方文档
项目中应用
首先,创建一个js文件 (文件在项目中的路径 src/utils/index.js)并把需要向外暴露的方法、变量等export出去。
javascript
//src/utils/index.js
import axios from "axios";
function add() {
console.log("add");
}
function add2() {
console.log("add2");
}
export { add, add2, axios };
接着,开始配置vue.config.js文件 。
javascript
const { defineConfig } = require("@vue/cli-service");
const webpack = require("webpack");
const path = require("path");
module.exports = defineConfig({
productionSourceMap: false,
lintOnSave: false,
configureWebpack: {
plugins: [
//挂载全局方法
new webpack.ProvidePlugin({
FF: [path.resolve(__dirname, "src/utils/index")],
}),
],
},
});
最后,在该使用它的地方开始使用。(我是在About.vue中进行使用的,只进行了打印)
javascript
<template>
<div class="about">
<h1>This is an about page</h1>
</div>
</template>
<script setup>
import { onMounted } from "vue";
onMounted(() => {
console.log(FF);
});
</script>
控制台打印结果:【可以看出,FF 变量存储的就是index.js 模块中向外暴露的东西,如果我们想使用add方法,是不是可以直接FF.add()】

那稍微的改动一下vue.config.js文件,index.js文件和About.vue文件中内容都不变!!!

再来看下控制台输出内容:

修改 vue.config.js 文件内容和index.js文件中的内容再看控制台打印内容


控制台结果:

只修改 index.js文件,保持vue.config.js文件不变


输出结果:

OK!到这就结束了,可以自己手动测试一下。谨记,每次修改完 vue.config.js 文件要重启项目!!!