目标:转义自定义标签
工具
- webpack
第一步:初始化本地 webpack 文件夹
生成如下目录结构
第二步:建立本地 demo-loader文件夹,用于本地开发,调试
- 新建 index.js开发文件;
// index.js
const { prefixTag } = require('./tag-map.js')
module.exports = function (source) {
for (const prefix of Object.keys(prefixTag)) {
source = source.replace(new RegExp(`<${prefix}(?!-)`, 'g'), `<${prefixTag[prefix]}`)
.replace(new RegExp(`<\/${prefix}>`, 'g'), `<\/${prefixTag[prefix]}>`);
}
return source
}
- 开发 loader 需要 package.json,用于对 loader做一个简单的描述,记录;
// loader/package.json
{
"name": "demo-loader",
"version": "1.2.2",
"author": "zj",
"license": "MIT",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": ""
},
"dependencies": {
},
"devDependencies": {
"webpack": "^2.2.1",
"loader-utils": "^1.1.0"
}
}
- tag-map.js 文件为了测试 demo,直接的拷贝了 iview 的标签loader文件;
// loader/tag-map.js
exports.tag = {
'Switch': 'i-switch',
'Circle': 'i-circle'
};
exports.prefixTag = {
'i-affix': 'Affix',
'i-alert': 'Alert',
'i-anchor': 'Anchor',
'i-anchor-link': 'AnchorLink',
...
};
第三步:对 loader 进行本地配置
- 配置 webpack的resolveLoader模块属性
// webpack.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const path = require('path')
module.exports = {
output: {
filename: '[name].js',
path: __dirname + '/dist'
},
entry: {
app: './index.js'
},
devServer: {
contentBase: './dist'
},
module: {
rules: [
{
test: /\.html$/,
use: [
'html-loader',
'demo-loader'
]
}
],
},
resolveLoader: {
// wepback 默认先在node_modules文件夹下查找,找不到就去后面的loaders路径下查找
modules: [
'node_modules',
path.join(__dirname, 'loader')
]
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
title: 'app'
})
]
}
第四步:运行项目
- input
// index.js
import tag from './test.html'
console.log('tag:', tag)
// test.html
<i-affix>fkewjfkjwefl</i-affix>
- output
以下为 package.json
{
"name": "demo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "webpack-dev-server --open",
"build": "webpack"
},
"author": "",
"license": "ISC",
"devDependencies": {
"clean-webpack-plugin": "^3.0.0",
"html-loader": "^1.3.2",
"html-webpack-plugin": "^4.5.0",
"loader-utils": "^2.0.0",
"webpack": "^4.17.1",
"webpack-cli": "^3.3.9",
"webpack-dev-server": "^3.8.2"
}
}