项目网址: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中:
本文 完。