- Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
background
In our VUE project, we may have many components that need to be registered globally. Have you ever encountered such trouble that there are too many components that need to be registered one by one?
Require. context is what?
Require.context is the Webpack API, and we can create our own context using require.context().
The basic usage of require.context
Syntax is as follows
require.context(
directory,
(useSubdirectories = true),
(regExp = / ^ \ \ /. * $/),
(mode = 'sync'));Copy the code
Example: require.context can pass three parameters: a directory to search, a flag to indicate whether subdirectories should also be searched, and a regular expression to match files
require.context("@/views/pageComponents".true./.vue$/)
// Create a context where the file comes from a non-pagecomponents directory and request ends with a '. Vue 'file
Copy the code
Pay attention to the point
A context Module exports a (require) function that takes a single argument: request. This export function has three attributes: resolve, keys, and ID.
Function returned
webpackContext(req) {
var id = webpackContextResolve(req);
return __webpack_require__(id);
}
Copy the code
Require.content application scenario
Case 1
In the vUE project, we encapsulated many components, so that the pages needed to be introduced one by one.
Method of use
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
})
Copy the code
Case 2
Load all images
<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>
Copy the code