Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

About webpack loader

In the process of learning Webpack, it is unavoidable to deal with loader and plugin, and writing a custom loader or plugin is one of the best ways to check your learning results.

Let’s write a simple markdown-loader.

Initialize the project

Create a file

  • First, we need to initialize our project to includehtml, andmain.tsFile and usewebpackPerform related configurations.

package.json:

{" name ":" webpack - loader - demo - 1 ", "version" : "1.0.0", "license" : "MIT", "dependencies" : {" @ Babel/core ": 7.12.3 "@", "Babel/generator" : "7.12.5", "@ Babel/parser" : "7.12.5", "@ Babel/preset - env" : "7.12.1", "@ Babel/traverse by" : "" @ types/babel__traverse 7.12.5", ":" 7.0.15 ", "HTML - loader" : "^ 2.1.2", "HTML - webpack - plugin" : "^ 5.4.0", "marked" : "^ 3.0.7 shelljs", "" :" 0.8.4 ", "ts - node" : "9.0.0", "typescript" : "4.0.5", "webpack" : "^ 5.59.0"}, "devDependencies" : {" @ types/babel__core ":" 7.1.12 ", "@ types/babel__generator" : "7.6.2", "@ types/babel__parser" : 7.1.1 ""," @ types/babel__preset - env ":" 7.9.1 ", "@ types/node" : "14.14.6", "@ types/shelljs" : "0.8.8", "Babel - loader" : "^ 8.2.2 ts -", "loader" : "^ 9.2.6", "webpack - cli" : "^ 4.9.1"}}Copy the code

webpack.config.js:

const path = require('path') const HtmlWebpackPlugin = require('html-webpack-plugin') const rootDir = process.cwd() module.exports = { mode: 'production', entry: './src/main.ts', output: { filename: 'bundle.js', path: path.join(__dirname, 'dist'), }, module: { rules: [ { test: /.(ts|tsx)$/, use: [ 'babel-loader', { loader: 'ts-loader', options: { happyPackMode: true, transpileOnly: true, }, }, ], exclude: /node_modules/, } ] }, plugins: [ new HtmlWebpackPlugin({ template: path.resolve(rootDir, 'public/index.html'), inject: 'body', scriptLoading: CollapseWhitespace: true, // Delete blank and newline characters},})]}Copy the code

throughyarn installInstallation-dependent dependencies

Create entry file

Create a public/index.html file in the root directory and say:

<! doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, User - scalable = no, initial - scale = 1.0, the maximum - scale = 1.0, Minimum scale=1.0"> <meta HTTP-equiv =" x-UA-compatible "content=" IE =edge"> <title>Document</title> </head> <body> </body>  </html>Copy the code

Create SRC /main.ts and SRC/readme. md files in the root directory

// src/main.ts
import readme from './README.md'

const div = document.createElement('div')
div.innerHTML = readme
document.body.appendChild(div)
Copy the code
// SRC/readme. md # Hello test markdown-loader # Hi here is the second lineCopy the code

Now that the preparation is complete, let’s write our loader!

Start writing loader!

writemarkdown-loader.js

  • Create it in the root directorymarkdown-loader.jsFile:
function transform (source) { const html = 'test' return `export default ${JSON.stringify(html)}`; } module.exports = transformCopy the code
  • inwebpack.config.jsUse ours inloader
module.exports = { //... Module: {rules: / / /... {test: /. Md $/, / / match the entry file is loaded into the md file use: ['/markdown - loader ']}]}}Copy the code

First test

Run YARN Build and open the index. HTML file in the dist directory to view the content

As you can see, the page is exactly what we wrotetestThe string

Use marked to convert strings

yarn add marked
Copy the code
//markdown-loader.js
const marked = require('marked')

function transform (source) {
  const html = marked(source)
  return `export default ${JSON.stringify(html)}`;
}

module.exports = transform
Copy the code

Fourth test

Run YARN Build and open the index. HTML file in the dist directory to view the content

Achieve the goal!

conclusion

The essence of webpack loader is to wrap non-JS content into JS code in the form of export default ${json.stringify (text)} that can be run

Source warehouse

Github.com/wbh13285517…