In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article focuses on "how to develop a Webpack Loader quickly". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to develop a Webpack Loader quickly.
Loader as the core mechanism of Webpack, the internal working principle is very simple. Next, let's develop our own Loader, and through this development process, we can gain an in-depth understanding of how Loader works.
My requirement here is to develop a loader that can load markdown files so that md files can be imported directly into the code. We should all know that markdown generally needs to be converted to html and then rendered to the page, so I want to import the md file and get the html string converted by markdown directly, as shown in the following figure:
Because of the need for a visual demonstration here, I will no longer create a separate npm module, but directly create a markdown-loader.js file in the project root directory, when you are finished, you can publish this module to npm as a separate module to use.
The project structure and core code are as follows:
└─ 03-webpack-loader sample root dir ├── src source dir │ ├── about.md markdown module │ └── main .js entry module ├── package.json package file ├── markdown-loader.js markdown loader └── webpack.config.js Webpack config file # About this is a markdown file.//. / src/main.js import about from'. / about.md' console.log (about) / / hopefully about = > 'About
This is a markdown file.
'
Each Webpack Loader needs to export a function, this function is our Loader processing of resources, its input is the content of the loaded resource file, the output is the result of our processing. We receive input through the source parameter and output by returning a value. Here, we first try to print source, and then return a string 'hello loader ~' directly inside the function. The specific code is as follows:
/ /. / markdown-loader.jsmodule.exports = source = > {/ / loaded module content = >'# About\ n\ nthis is a markdown file.'console.log (source) / / the returned value is the final packaged content return 'hello loader ~'}
When we are finished, we go back to the Webpack configuration file to add a loader rule, where the matching extension is .md, and the loader used is the markdown-loader.js module we just wrote. The specific code is as follows:
/. / webpack.config.jsmodule.exports = {entry:'. / src/main.js',output: {filename: 'bundle.js'}, module: {rules: [{test: /\ .md $/, / / directly use the relative path use:'. / markdown-loader'}]}}
TIPS: the use attribute here can use not only the module name but also the module file path, which is the same as the require function in Node.
After the configuration is complete, we open the command line terminal again and run the packaging command, as shown in the following figure:
During the packaging process, the command line does print out the contents of the Markdown file we imported, which means that the arguments to the Loader function are indeed the contents of the file.
But also reported a parsing error that said: You may need an additional loader to handle the result of these loaders. (we may also need an additional loader to handle the results of the current loader.)
So why on earth is this? In fact, the process of Webpack loading resource files is similar to a working pipeline, you can use multiple Loader in turn in this process, but the end result of this pipeline must be a standard JS code string.
That's why we have the above-mentioned error here, and the solution is obvious:
Return a JS code string directly at the end of the Loader
Find a suitable loader and then deal with the results we get here.
Let's try the first method first. Back in markdown-loader, we modify the contents of the returned string to console.log ('hello loader~'), and then run packaging again, so that Webpack will no longer report an error, as shown in the following code:
/ /. / markdown-loader.js module.exports = source = > {/ / loaded module content = >'# About\ n\ nthis is a markdown file.' Console.log (source) / / the returned value is the final packaged content / / return 'hello loader ~' return 'console.log ("hello loader ~")'}
What is the result of packing at this time? We open the output bundle.js and find the last module (because the md file was introduced later), as shown in the following figure:
This module is very simple, that is, we just returned the string directly into the module. This also explains why the Loader pipeline finally had to return the JS code, because if you return anything at random, the syntax will fail here.
# implement the logic of Loader
With a general understanding of how Loader works, let's go back to markdown-loader.js and finish my requirements. Here you need to install a module called marked that can parse Markdown into HTML.
After the installation is complete, we import the module in markdown-loader.js and use this module to parse our source. The result of parsing here is a HTML string. If we return it directly, we will also face the problem that Webpack cannot parse the module. The correct way is to concatenate this HTML string into a piece of JS code.
At this point, the code we want to return is to export the HTML string through module.exports so that the HTML string can be received by the outside world when the module is imported. If you simply concatenate, then line breaks and quotation marks in HTML may cause syntax errors, so I use a little trick here, as follows:
/. / markdown-loader.js const marked = require ('marked') module.exports = source = > {/ / 1. Convert markdown to html string const html = marked (source) / / html = > 'About
This is a markdown file.
/ / 2. JS code const code = `module.exports = ${JSON.stringify (html)} `return code / / code = > 'export default "About to concatenate a html string into an exported string
This is a markdown file.
"'}
Convert the field string to a standard JSON string through JSON.stringify (), and then participate in stitching, so there will be no problem.
Let's go back to the command line and run the package again, and the result is what we need.
In addition to module.exports, Webpack also allows us to use ES Modules to export in the returned code. For example, here we change module.exports to export default, and then run packaging. The result is also possible, and the ES Modules code will be automatically converted within Webpack.
/ /. / markdown-loader.js const marked = require ('marked') module.exports = source = > {const html = marked (source) / / const code = `module.exports = ${JSON.stringify (html)} `const code = `export default ${JSON.stringify (html)} `return code} # Cooperation of multiple Loader
We can also try the second idea we just mentioned, which is to return the HTML string directly in our markdown-loader and hand it over to the next Loader for processing. This involves multiple Loader working together.
Let's go back to the code, where we directly return the HTML parsed by marked, as shown below:
/. / markdown-loader.js const marked = require ('marked') module.exports = source = > {/ / 1. Convert markdown to html string const html = marked (source) return html}
Then we install a Loader that handles HTML, called html-loader, with the following code:
/. / webpack.config.js module.exports = {entry:'. / src/main.js', output: {filename: 'bundle.js'}, module: {rules: [{test: /\ .md $/, use: [' html-loader','. / markdown-loader']}]}}
Go back to the configuration file after installation, where you also change the use property to an array to use multiple Loader in turn. However, it is also important to note that the order of execution here is from back to front, which means that we should put the first executed markdown-loader in the back and the html-loader in front.
When we are finished, we go back to the command line terminal to pack again, and the packaging result here is still OK.
At this point, we have completed the markdown-loader module, in fact, the whole process focuses on the working principle and implementation of Loader.
At this point, I believe you have a deeper understanding of "how to develop a Webpack Loader quickly". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
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.