Require statement with expression

If your require parameter contains expressions, a context will be created because it is not clear at compile time which module is imported

require("./template/" + name + ".ejs");
Copy the code

Webpack parses the call to require() and extracts the following information:

Directory: ./template
Regular expression: /^.*\.ejs$/
Copy the code

All references to modules with the suffix. Ejs in the template directory, including subdirectories, are returned.

require.context

You can create your own (module) context using the require.context() method, which takes three parameters:

  • The folder directory to search for
  • Should I also search its subdirectories,
  • And a regular expression that matches the file.

  require.context(directory, useSubdirectories = false, regExp = /^\.\//)
 

  require.context("./test".false, /\.test\.js$/); // create a file containing thetestThe context of all files under folders (excluding subdirectories) whose names end in '.test.js' that can be requested by require. require.context(".. /".true, /\.stories\.js$/); // a context containing all files under the parent folder (including subdirectories) whose names end in '.stories.js'.Copy the code

The require.context module exports (and returns) a (require) function that takes one argument: the request function — here request should be an expression in the require() statement

The exported method has three attributes: resolve, keys, and ID.

  • Resolve is a function that returns the module ID after the request is resolved.
  • Keys is also a function that returns an array of all the requests that might be processed by the context module.
  • Id is the module ID contained in the context module. It may be used when you use module.hot.accept

Vue global components:


module.exports.install = function(Vue) {/* All. Vue components in the./components directory are automatically registered as global components with <mv-***></mv-***> as the component label name, *** is the component. Name, */ const requireAll = context => context.keys().map(context); const component = require.context('./components'.false, /\.vue$/);
 // const directive = require.context('./directives'.false, /\.js$/);

 requireAll(component).forEach((item) => {
   const name = (item.name || /(\S+\/)(\S+)\.vue/.exec(item.hotID)[2]).toLowerCase();
   Vue.component(`mv-${name}`, item);
 });

};


Copy the code

/**
* The file enables `@/store/index.js` to import all vuex modules
* in a one-shot manner. There should not be any reason to edit this file.
*/

const files = require.context('./modules'.false, /\.js$/)
console.log('-- -- -- -- -- -- -- -- -- -- -- --')
console.log(files.keys())
console.log('-- -- -- -- -- -- -- -- -- -- -- --')
const modules = {}

files.keys().forEach(key => { 
   modules[key.replace(/(\.\/|\.js)/g, ' ')] = files(key).default
})

console.log('-- -- -- -- -- -- -- -- -- -- -- --')
console.log(modules)
console.log('-- -- -- -- -- -- -- -- -- -- -- --')
export default modules

Copy the code

To import all SVG files under SVG, create a new js file named index.js in the ICONS directory and write the following code:

let requireAll = requireContext => requireContext.keys().map(requireContext)
let req = require.context('./svg'.false, /\.svg$/)
requireAll(req) 
Copy the code

Vue global components

const requireAll = context => context.keys().map(context);

const component = require.context('./components'.false, /\.vue$/);   // falseInstead of iterating through subdirectories,trueRequireAll (Component).foreach (({default:item}) => {console.log(item) Vue.component(' wb-${item.name}`, item);
});
Copy the code

Uppercase

Object.keys(components).forEach((key) => { var name = key.replace(/(\w)/, (v) => v.toupperCase ()) // uppercase Vue.component(' v${name}`, components[key])
})
Copy the code

Use require.context to traverse all images in the directory

G: Code\Vue\vue-global-component\ SRC \assets>tree /f volume PATH list 1081-0973 G:.│ logo.png ├ ─kittens kitten1.jpg kitten2.jpg kitten3.jpg kitten4.jpgCopy the code

Load all images

<template>
	<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

import Vue from 'vue'

 

function capitalizeFirstLetter(string) {

  return string.charAt(0).toUpperCase() + string.slice(1)

}

 

const requireComponent = require.context(

  '. '.false. Requirecomponent.keys ().foreach (fileName => {const componentConfig = const componentConfig =) // requireComponent(fileName) const componentName = capitalizeFirstLetter( fileName.replace(/^\.\//,' ').replace(/\.\w+$/, ' '// Because the resulting filename format is:'./baseButton.vue', so here we go to turn around and tail, only keep the real name) Vue.com ponent (the componentName, componentConfig. Default | | componentConfig)})Copy the code
import Vue from 'vue'
let contexts = require.context('. '.false, /\.vue$/)
contexts.keys().forEach(component => {
  letVue.com Ponent (componentEntity = Context (Component). Default // Register global components using the built-in component name. Vue.com Ponent (ComponentEntity. name, componentEntity) })Copy the code