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中:

本文 完。

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值