In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Today, the editor will share with you how to use Vue3+Vite to import modules or resources in batches, with detailed content and clear logic. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.
1, pre-basic knowledge-JavaScript modular programming
In the past, when developing ordinary web programs, we directly used script tags to introduce js files to call its functions, but in vue you found that it was not, because vue also uses modular programming standards.
Usually we can call a js file which encapsulates a lot of functions and variables to be reused as a module. The module must expose (export) the variables and functions in order to be externally imported and call the functions.
There are now two common module standards: CommonJS and ES6.
Here we focus on the ES6 module.
(1) export statement-exposes functions and variables to make external calls
Now we create a js file to represent our own module, which encapsulates some frequently reused functions, variables, and so on, which need to be exposed using export.
/ / Export constant aexport const a = 'test';// export function myPrintexport function myPrint (msg) {console.log (' []'+ msg);}
It can be seen that you can add export in front of the variable / function when you define it.
In addition, you can also export in bulk:
Const a = 'test';function myPrint (msg) {console.log (' []'+ msg);} / export constant an and function myPrintexport {a, myPrint}; (2) import statement-import variables / functions and use
Functions, variables, and so on are encapsulated and exported, but they cannot be used directly. You need to import where you want to use it:
/ / Import function myPrint and constant aimport {a, myPrint} from'. / mymodule.js';// uses the imported variable and function console.log (a); myPrint ('msg')
So it can be used.
You can see that the import syntax is as follows:
Import {variable 1 / function 1, variable 2 / function 2, variable 3 / function 3,...} from'js file path'
It should be noted that there can be more than one imported variable and function at a time, enclosed in curly braces, and the imported variable / function name must be the same as the one exported in the module!
(3) import * as xxx statement-Import all
For the modules that need to be imported, we need to write a long list of imported variables and functions after import, so we can import them all at once.
For the above mymodule, a variable and a function are exported, and here we can import them all at once:
/ / Import the contents of the module all at once and name it myimport * as my from'. / mymodules.js';// call module attribute aconsole.log (my.a); / / call module function myPrintmy.myPrint ('hhh')
It can be seen that using the import * as name from 'module path' can not only easily import all the contents of a module js file, but also define a name to make it easy to call.
(4) export default-default export
The above export method is actually named export, and the variable / function names of other files must be the same as those exported in the module.
But sometimes what if we don't know the function / variable name in the js file we're going to import?
You can use the default export, that is, the export default statement, for example, to export a function by default:
/ / Export the myPrint function export default function myPrint (msg) {console.log ('[]'+ msg) by default;}
After the default export, you can name it yourself when importing:
/ / Import the default exported function / variable in the file and name it pimport p from'. / mymodule.js';// using p ('msg')
It can be seen that curly braces are not used here, and you can name them when you import them, and you don't need to have the same function name as in the original module.
Note that a js file can only have one default export! You cannot export by default multiple times!
So, for a reuse module with a lot of variables and functions, we can write:
Export default {/ / variable aa: 'asides, / / function myPrint myPrint () {console.log (' aa');}}
When called:
Import m from'. / mymodule.js';// uses console.log (m. A); m.myPrint ()
Obviously, a large anonymous JavaScript object is directly exported by default, and variables and functions are written in this object. Then import and call the variable / function.
In fact, many of the external JavaScript libraries we use in vue development are done this way.
In fact, isn't the principle of our Vue single file component the same?
2. Import js modules in batch in Vite project.
In previous Vue-cli development, we could use require.context () to implement batch imports. However, because Vite is entirely based on the ES6 module, this approach cannot be used.
Of course, the official also provides a way to achieve batch import, using import.meta.glob or import.meta.globEager functions. The former is a lazy import, while the latter is a direct import. Today, I will mainly talk about the latter.
For example, I now have three js files under src/assets/js in the project directory:
Now that you want to bulk import them in the root component App.vue, write at the beginning of the section:
Const importModules = import.meta.globEager ('. / assets/js/*.js')
This imports all the js module files under. / assets/js.
Of course, this method can also match multi-level directories:
Const importModules = import.meta.globEager ('. / assets/js/**/*.js')
This imports all js files under. / assets/js and all js files in their subdirectories.
Here we import it as a variable importModules. What exactly is in this variable? Let's print it in the mounted function to see:
Console.log (importModules)
It can be seen that what is imported is an object, each attribute in this object is the module path, and the default attribute in the corresponding value is the imported module itself, the function variables of the module, and so on. So we can call our module by taking the default attribute under each attribute of the imported variable.
For example, you will now call the print function in the module one:
ImportModules ['. / assets/js/one.js'] .default.print ('hello')
At this point, I believe you have found the problem again: every time you call a batch imported module, you have to use the full path of the module to get it, and you also need to bring the default attribute, which is inconvenient.
Can we use the module name (js file name) to retrieve the corresponding module? Of course. In fact, there are many ways. Let me tell you my way of thinking.
Why don't we just replace each attribute name in the variable importModules that stores the import module with the module name by string clipping, and directly replace the value of each attribute with its default value? Let's give it a try:
/ / process the objects imported into the storage module in batch / / get all their attributes const keys = Object.keys (importModules) first; / / perform the batch replacement operation for (let path of keys) {/ / cut the string to get the file name in the path (no extension) let name = path.substring (path.lastIndexOf ('/') + 1, path.lastIndexOf ('.js')) / / add a new attribute to the original object and delete the old attribute to achieve the processing effect importModules [name] = importModules [path] .default; delete importModules [path];}
Now, we can easily call it!
/ / call module one's printimportModules.one.print ('hello'); / / print module two's name attribute console.log (importModules.two.name); 3. Import static resources such as pictures / audio in bulk in the Vite project.
In Vite, if you want to dynamically bind pictures, audio, video, etc., you also need to use import statements. Similarly, if you have more pictures, what should you do if you don't want to import one by one?
In fact, we can also use import.meta.globEager to import static resources such as pictures and audio in bulk.
Suppose there are a lot of pictures under src/assets/image.
We can still import in bulk as described above:
Const importImages = import.meta.globEager ('. / assets/image/*')
The method is exactly the same as above, except that the static resources are imported this time, so the default of the above importImages becomes the path of the corresponding resources.
Print it and have a look:
Similarly, we can save each default imported above and render it in batch using v-for. For a try, the code of the entire Vue file is as follows:
Const importImages = import.meta.globEager ('. / assets/image/*'); export default {data () {return {/ / store bulk imported images images: []}}, mounted () {/ / take each default attribute in the imported object (corresponding to the actual imported picture) into the variable images in data and for (let path in importImages) {this.images.push (importImages [path] .default);}
Effect:
These are all the contents of the article "how to use Vue3+Vite to import modules or resources in bulk". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.