天天看點

Webpack5 - 自定義一個Loader-來加載markdown(.md)檔案

項目網址:https://gitee.com/big-right-right/webpack-my-markdonw-loader

# 介紹

webpack自定義一個Loader, 用于加載markdown檔案資源。項目中把markdown檔案轉換為html并顯示在網頁中。

# 步驟

1. cnpm init -y

2. cnpm i -D webpack webpack-cli

3. 建立 src 目錄,下面建 main.js 、content.md  、markdown-loader.js、 index.html 四個檔案。

main.js:

import content from './content.md';

document.getElementById('div1').innerHTML = content;
           

content.md:

# Markdown内容标題

## 内容一

## 内容二

一些詳細内容。
           

markdown-loader.js:

const marked = require('marked'); // 把 markdown 檔案轉換為 html 的子產品
module.exports = source => {
    const html = marked(source)
    return html
}
           

index.html:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Webpack 開發一個 Loader</title>
</head>
<body>
    <h1><%=  htmlWebpackPlugin.options.title %></h1>
    <div id="div1"></div>
</body>
</html>
           

4. package.json 開發依賴:

"devDependencies": {
    "html-loader": "^1.3.2",
    "html-webpack-plugin": "^4.5.0",
    "marked": "^1.2.7",
    "webpack": "^5.11.0",
    "webpack-cli": "^4.3.0"
  }
           

5. webpack.config.js:

const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')

/** @type { import('webpack').Configuration } */
module.exports = {
    mode: 'production',
    entry: './src/main.js',
    output: {
        filename: 'bundle.js',
        path: path.join(__dirname, 'output'),
    },
    module: {
        rules: [
            {
                test: /\.md$/,
                use: [
                    'html-loader',              // 處理 markdown 文本轉換的html, 把html打包到js檔案中
                    './src/markdown-loader.js'  // 把 markdown 文本轉換為 html
                ]
            }
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({  // 以 src/index.html 為模闆,生成 html 檔案到output檔案夾
            title: 'My Markdown Loader',
            template: './src/index.html'
        })
    ]
}
           

6. 執行打包 - 執行完畢則打包成功,output檔案夾已生成,其中包含了index.html 和 bundle.js 兩個檔案:

yarn webpack
           

7. 運作 output 檔案夾中的 index.html,效果如下 - content.md 中的内容已被渲染到html中:

Webpack5 - 自定義一個Loader-來加載markdown(.md)檔案

本文 完。