当前位置:网站首页>Let's customize the loader
Let's customize the loader
2022-07-25 02:01:00 【An ice cream】
loader stay webpack Compilation plays a very important role , Used to convert the source code of the module , such as css-loader take css The code is processed into a string ,style-loader establish style The label will css Code added to html On the page .
Customize loader
newly build node project , stay src Under folder index.js Simply write some code in
const user = {
name: 'alice',
age: 20,
};
establish loaders Folder , Add to the folder for processing loader Of js file , adopt module.exports Function can get the contents of the file to be processed , And return the processed results
module.exports = function (content) {
console.log('ice-loader>>', content);
return content + '"@author icecream"';
};
In profile webpack.config.js Introduce custom loader . Definition loader There are two ways
- Introduce... Through relative paths ( The way it's used here )
- adopt resolveLoader Attribute configuration , Default will go node_modules Query dependency
// Other configurations are omitted
module: {
rules: [
{
test: /\.js/i,
use: ['./loaders/ice-loader'],
},
],
},
adopt webpack Compile the file , Output the obtained file content on the console , The compiled file is customized loader What's coming back .

Synchronous asynchronous loader
adopt loader The processed data needs to be returned javscript character string , There are two ways
returnStatement returns the contentthis.callbackReturns the function content
When encountering asynchronous return , Using the above two methods directly will report an error

Need to pass through this.async Function to make the process asynchronous ,this.callback The first parameter receives error, If there is no error, pass null, Other parameters are related to loader in module.exports The obtained parameters are the same

babel-loader
babel-loader Handle js The code relies on babel This tool , We can also easily implement one , named ice-babel-loader, Use babel You need to go through plugin perhaps presets Define processing rules
{
test: /\.js/i,
use: [
{
loader: './loaders/ice-babel-loader',
options: {
presets: ['@babel/preset-env'],
},
},
],
},
babel The core library of tools is @babel/core, Defining processing rules requires presets @babel/preset-env, In turn, installation
const babel = require('@babel/core');
module.exports = function (content) {
const options = this.getOptions(); // obtain loader As defined in options
const callback = this.async();
babel.transform(content, options, (err, result) => {
if (err) callback(error);
callback(null, result.code);
});
};
So we define ice-babel-loader will es6 The grammar of is changed to es5

md-loader
Markdown It's a lightweight markup language , It allows people to write documents in plain text format that is easy to read and write , And then convert it into effective XHTML( perhaps HTML) file .
that md Whether the document can pass loader convert to html Documents ? The answer is yes , There are already some useful libraries that provide us with this function .
marked Used for processing markdown File format ,highlight.js For giving markdown The code in the file sets the style
const {
marked } = require('marked');
const hljs = require('highlight.js');
module.exports = function (content) {
// to markdown Add code in class attribute
marked.setOptions({
highlight: function (code, lang) {
return hljs.highlight(lang, code).value;
},
});
const htmlContent = marked(content);
return htmlContent;
};
At this point through md-loader The returned string is a normal string , Can not be javascript Identified by code , It also needs to go through html-loader Handle .
{
test: /\.md/i,
use: ['html-loader', './loaders/md-loader'],
},
adopt loader After processing the md The file is exported javascript character string , So it can be directly added to body View the effect , In addition, the style display of code needs to be introduced highlight.js Medium css file
// index.js
import code from './doc.md';
import 'highlight.js/styles/default.css';
document.body.innerHTML = code;
such markdown The file can be parsed into html On the page

summary
- Customize loader adopt module.exports Get resource content , After a series of processing and return the processed results .
- self-written loader You can set up folders locally to process resources , After development, it will be released to npm The warehouse can directly reference by downloading packages loader.
That's about Customize loader Introduction to , More information about webpack You can refer to my other blog posts , Ongoing update ~
边栏推荐
- Visual studio code installation package download slow & Installation & environment configuration & new one-stop explanation
- Use SAP ui5 application to consume create and delete operations of OData in business application studio
- Create the first hbuilder project
- [linear DP] Digital triangle
- Harbor installation
- PostgreSQL views tables, table indexes, views, table structures, and parameter settings
- Upgrade the leapfrog products again, and the 2023 Geely Xingrui will be sold from 113700 yuan
- Resolution of multi thread conflict lock
- Chinese son-in-law OTA Ono became the first Asian president of the University of Michigan, with an annual salary of more than 6.5 million!
- 2022/7/18-7/19
猜你喜欢

Kernel structure and design

6-10 vulnerability exploitation SMTP experimental environment construction

Visual studio code installation package download slow & Installation & environment configuration & new one-stop explanation

Peripherals: timer, watchdog and RTC

Harbor installation

From casting sword to defending sword: the way to build the efficiency platform of didi project

Green low-carbon Tianyi cloud, a new engine of digital economy!

Using multithreaded execution method in Lua script based on nlua implementation

High performance memory recovery technology for decrypting ark -- HPP GC

Start to build a three node Eureka cluster
随机推荐
Ecosystem long-term observation data product system
G024-db-gs-ins-01 openeuler deployment opengauss (single instance)
Harbor installation
The introduction of 23 Filipino doctors for 18million was a hot topic, and the school teacher responded: expedient
Kernel structure and design
Automatically create partition tables by time and month in PostgreSQL
"Ask the sky" is in place! Yu Jingchuan's "China Space Station" in 2013 is about to set sail in the sea of stars
Industrial control safety PLC firmware reverse II
Performance analysis method - Notes on top of performance
SetTimeout parameters [easy to understand]
Target segmentation for 10000 frames of video, less than 1.4GB of video memory, open source code | ECCV 2022
Deamnet|filenotfounderror: [winerror 3] the system cannot find the specified path.: '/ Datasettest\\Set12‘
Hongmeng harmonyos 3 official announcement: officially released on July 27; Apple slowed down the recruitment and expenditure of some teams in 2023; Russia fined Google 2.6 billion yuan | geek headlin
6-10 vulnerability exploitation SMTP experimental environment construction
Scalar, vector, matrix calculus
Detailed explanation of MySQL, Oracle and PostgreSQL database index failure scenarios
Speed comparison between 64 bit width and 32 bit width of arm64 memory
JS utils tool function that makes you get twice the result with half the effort
[recognize cloud Nativity] Chapter 4 cloud network section 4.9.4.3 - smart network card usage scenario - network acceleration implementation
2022.7.20 linear table