We know that Webpack itself can only parse JS files, but there will be HTML, CSS, images and other file types in our project. At this time, we need Loader to help us convert these files into effective modules that WebPack can process.
What is the loader?
Loader is used to convert the module source code. Loader allows you to preprocess files when importing or “loading” modules. As such, Loader is similar to “tasks” in other build tools and provides a powerful way to handle the front-end build steps. K can convert files from different languages (such as TypeScript) to JavaScript, or convert inline images to data urls. Loader even allows you to import CSS files directly into JavaScript modules!
Loader itself is a function that takes the source code as an input and outputs the compiled code.
Using the loader
The most commonly used is to specify loader webpack.config.js in webpack.config.js
module: {
rules: [
{
test: /\.css$/,
use: [
{ loader: 'style-loader' },
{
loader: 'css-loader',
options: {
modules: true}}]}Copy the code
Test Sets the file matching rule
Use Specifies the loader to be used
Options indicates the loader configuration item
Note: The loader is executed from right to left
The commonly used loader
Ok, let’s take a look at some commonly used loaders
Parsing es6
Use babel-loader, which depends on Babel, so you need a configuration file. Babelrc
To parse ES6, add the following configuration to babelrc:
{
"presets": [
"@babel/preset-env"]}Copy the code
Next, configure webpack.config.js
module: {
rule: [
{
test: /\.js$/,
use: ['babel-loader'],
exclude: '/node_modules/'}}]Copy the code
Parsing JSX
/ / add react to babelrc
{
"presets": [
"@babel/preset-env"."@babel/preset-react"]}Copy the code
The above webpack. Config. Js
Parsing the CSS
Use csS-loader and style-loader to load. CSS files and convert them to commonJs objects. Style-loader inserts the styles into the head using the
Configuration webpack. Config. Js
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader'.'css-loader']]}}Copy the code
Parse less and sass
Less uses less-loader. Sass Uses sas-loader
Both loaders convert files to CSS and then export them to the page through CSS-loader and style-loader
webpack.config.js
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader'.'css-loader'.'less-loader']]}}Copy the code
Resolution images
1.file-loader webpack.config.js
module: {
rules: [
{
test: /\.(png|svg|jpg|gif)$/,
use: ['file-loader']]}}Copy the code
2. Url-loader The url-loader function is similar to that of file-loader, except that a small resource can be transferred to Base64
webpack.config.js
module: {
rules: [
{
test: /\.(png|svg|jpg|gif)$/,
use: [{
loader: 'url-loader',
options: {
limit}}]}Copy the code
Limit is the limit on the conversion size.
Link to the article
Webpack-hot-middleware enables hot updates
Webpack-dev – Middleware
Webpack-dev-server implements hot update
Webpack learning path (1) basic configuration
I am moving forward.