webpack配置ProvidePlugin后,在使用时将不再需要import和require进行引入,直接使用即可。
使用方法:
在webpack.dev.conf.js和webpack.prod.conf.js中添加
1 plugins: [2 ...3 new webpack.ProvidePlugin({4 ‘api‘: ‘api‘5 }),6 ...7 ]
使用场景:
将所有接口调用方法放在 src/api/index.js中,在组件中无需import即可调用
相关配置:
在webpack.base.conf.js中添加
1 resolve: {2 extensions: [‘.js‘, ‘.vue‘, ‘.json‘],3 alias: {4 ‘vue$‘: ‘vue/dist/vue.esm.js‘,5 ‘@‘: resolve(‘src‘),6 ‘api‘: resolve(‘src/api/index.js‘),7 }8 },
在组件中使用:
1 ...2 mounted() {3 api.getData().then(res => {4 this.items = res5 }).catch(err => {6 console.log(err)7 })8 },9 ...