Goal: To escape custom tags

tool

  • webpack

Step 1: Initialize the local WebPack folder

Generate the following directory structure

Step 2: Create a local demo-loader folder for local development and debugging

  1. Create a new index.js development file.
// 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 }Copy the code
  1. Package. json is required for loader development, which is used to make a simple description and record of loader.
/ / loader/package. Json {" name ":" demo - loader ", "version" : "1.2.2", "author" : "what zj had", "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"}}Copy the code
  1. Tag-map. js file to test the demo, directly copy the iView tag loader file;
// 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',
  ...
 };
Copy the code

Step 3: Configure loader locally

  1. Configure the resolveLoader module properties for WebPack
// 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 defaults to node_modules and loaders to modules: [ 'node_modules', path.join(__dirname, 'loader') ] }, plugins: [ new CleanWebpackPlugin(), new HtmlWebpackPlugin({ title: 'app' }) ] }Copy the code

Step 4: Run the project

  • input
// index.js
import tag from './test.html'

console.log('tag:', tag)

// test.html

<i-affix>fkewjfkjwefl</i-affix>
Copy the code
  • output

The following for the package. The 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", "- the utils" : "^ 2.0.0", "webpack" : "^ 4.17.1", "webpack - cli" : "^ 3.3.9", "webpack - dev - server" : "^ 3.8.2"}}Copy the code