我在 vue 项目中 使用 require.context 来自动引入组件 ,解放双手

1,395 阅读1分钟

背景

我们在vue项目中,我们可能或有很多的组件需要全局注册,大家有没有遇到这样的烦恼,组件太多,需要一个一个引入注册呢? c1e8c21daff72d7fd42e469fe289621.png

require.context 是什么?

require.context 是webpack的api,我们可以通过require.context()函数来创建自己的context。

require.context 的基本用法

语法如下

require.context(
  directory,
  (useSubdirectories = true),
  (regExp = /^\.\/.*$/),
  (mode = 'sync')
);

示例: require.context可以传三个参数:一个要搜索的目录,一个标记表示是否还搜索其子目录, 以及一个匹配文件的正则表达式

require.context("@/views/pageComponents",true,/.vue$/)
//  创建出一个context,其中文件来自非pageComponents目录, request以`.vue`文件结尾

注意点

一个 context module 会导出一个(require)函数,此函数可以接收一个参数:request。此导出函数有三个属性:resolve, keys, id。 返回的函数

webpackContext(req) {
	var id = webpackContextResolve(req);
	return __webpack_require__(id);
}

require.content 的应用场景

案例1

我们在vue项目工程中,封装了很多组件,让后在需要用到的页面需要一个一个引入,

使用方法

const pageComponents = require.context("@/views/pageComponents",true,/.vue$/)
export const components={}
pageComponents.keys().forEach(item=>{
    const name = path.basename(item,".vue")
    components[name] = pageComponents(item).default
})

案例2

加载所有的图片

	<div id="app">
		<img src="@/assets/logo.png">
		<li v-for="item in images">
			<h3>Image: {{ item }}</h3>
			<img :src="imgUrl(item)">
		</li>
	</div>
</template>

<script>
	var imagesContext = require.context('@/assets/kittens/', false, /\.jpg$/);
	console.log(imagesContext)
	console.log(imagesContext('./kitten1.jpg'))
	console.log(imagesContext.keys())
	export default {
		created: function() {
			this.images = imagesContext.keys();
		},
		name: 'haha',
		data() {
			return {
				images: [],
				msg: 'Welcome to Your Vue.js App'
			}
		},
		methods: {
			imgUrl: function(path) {
				//console.log('Path:' + path);
				return imagesContext(path)
			}
		}
	}
</script>

<style>
	#app {
		font-family: 'Avenir', Helvetica, Arial, sans-serif;
		-webkit-font-smoothing: antialiased;
		-moz-osx-font-smoothing: grayscale;
		text-align: center;
		color: #2c3e50;
		margin-top: 60px;
	}
	
	h1,
	h2 {
		font-weight: normal;
	}
	
	ul {
		list-style-type: none;
		padding: 0;
	}
	
	li {
		display: inline-block;
		margin: 0 10px;
	}
	
	a {
		color: #42b983;
	}
</style>