Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add new plugin tag-modify #287

Merged
merged 2 commits into from
Nov 26, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions packages/wxa-plugin-tag-modify/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules
.DS_Store
1 change: 1 addition & 0 deletions packages/wxa-plugin-tag-modify/.npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
node_modules
Empty file.
21 changes: 21 additions & 0 deletions packages/wxa-plugin-tag-modify/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 hughliu

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
37 changes: 37 additions & 0 deletions packages/wxa-plugin-tag-modify/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# wxa-plugin-tag-plugin

打包阶段批量修改wxml标签

## install
```
npm install -S @wxa/plugin-tag-modify
```


## Usage
### 在wxa打包配置中使用
使用插件时,需要实例化插件并传入参数,支持拦截所有事件和指定拦截事件
```javascript
// wxa.config.js
const BindHijackPlugin = require('@wxa/plugin-bind-hijack');

module.exports = {
resolve: {
alias: {
'@': path.join(__dirname, 'src'),
},
},
use: ['babel', 'sass'],
plugins: [
// 批量修改image标签,增加binderror属性、调整src
new TagModifyPlugin([{
target: 'image',
operateFn: (attribs) => {
if (!attribs.binderror) attribs.binderror = 'imageOnError';
if (attribs.src) attribs.src = attribs.src.replace('WEB_STATIC_URL', '{{CDNBaseUrl}}');
return attribs;
}
}])
]
}
```
107 changes: 107 additions & 0 deletions packages/wxa-plugin-tag-modify/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
var debug = require('debug')('WXA:PLUGIN-REPLACE')
var htmlparser2 = require('htmlparser2');

let { Parser, DomHandler, DomUtils } = htmlparser2;

module.exports = class TagModifyPlugin {
constructor(options = []) {
this.configs = Object.assign({}, {
test: /\.wxml$/,
plugins: []
}, { options });
this.pmap=['<', '&', '"', '>'];
this.amap=['&lt;', '&amp;', '&quot;', '&gt;'];
}
apply(compiler) {
if (compiler.hooks == null || compiler.hooks.buildModule == null) return;

compiler.hooks.buildModule.tap('TagModifyPlugin', (mdl) => {
if (
mdl.meta &&
this.configs.test.test(mdl.meta.source)
) {
debug('Plugin TagModify started %O', mdl.src);
this.run(mdl);
}
})
}
run(mdl) {
if (mdl.content && mdl.content.replace) {
let configsOptions = this.configs.options;

const {
target,
operateFn = () => {}
} = configsOptions;

let handler = new DomHandler((err, dom) => {
if (err) {
logger.error('XML错误:'+mdl.meta.source);
logger.error(err);
}
}, {
normalizeWhitespace: true, //default:false
});

let htmlStr = mdl.content.replace(/{{([^{}]*)}}/g, (match, express) => `{{${this.encode(express)}}}`);
new Parser(handler, {
xmlMode: false, // forgiving html parser
recognizeSelfClosing: true,
lowerCaseTags: false, // needn't make tag lower case
lowerCaseAttributeNames: false,
recognizeCDATA: true,
}).end(htmlStr);

let dom = handler.dom;
let rewrite = function (dom) {
dom.forEach(v => {
configsOptions.forEach((action) => {
const { target, operateFn } = action;
if(v.attribs && v.name === target) {
const attribs = operateFn(v.attribs);
v.attribs = {
...v.attribs,
...attribs
}
}
});
if (v.children) {
rewrite(v.children);
}
});
}
rewrite(dom);

mdl.content = DomUtils.getOuterHTML(dom)
.replace(/{{([^{}]*)}}/g, (match, express) => `{{${this.decode(express)}}}`);
}
}
decode(content, pmap, amap) {
pmap = pmap || this.pmap;
amap = amap || this.amap;

let ret = amap.reduce((ret, item)=>(ret+'|'+item), '').replace(/^\|/, '');
let reg = new RegExp(`(${ret})`, 'ig');
return content.replace(reg, (match, m) => {
return pmap[amap.indexOf(m)];
});
}
encode(content, start, end, pmap, amap) {
start = start || 0;
end = end || content.length;
pmap = pmap || this.pmap;
amap = amap || this.amap;
let buffer = [];

for (let i=0, len=content.length; i < len; i++) {
if (i < start || i > end) {
buffer.push(content[i]);
} else {
let idx = pmap.indexOf(content[i]);
buffer.push(idx === -1 ? content[i] : amap[idx]);
}
}

return buffer.join('');
}
}
72 changes: 72 additions & 0 deletions packages/wxa-plugin-tag-modify/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

26 changes: 26 additions & 0 deletions packages/wxa-plugin-tag-modify/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
"name": "@wxa/plugin-tag-modify",
"version": "1.0.0",
"description": "batched modify tags",
"main": "index.js",
"scripts": {},
"keywords": [
"wxa",
"tag",
"modify"
],
"repository": "https://github.com/wxajs/wxa.git",
"homepage": "https://wxajs.github.io/wxa/",
"author": "hughliu",
"license": "MIT",
"publishConfig": {
"access": "public"
},
"devDependencies": {
"debug": "^4.1.1"
},
"gitHead": "b925c4fe80f493edd89c0c39a70e6eda3b97d915",
"dependencies": {
"htmlparser2": "^4.1.0"
}
}
Loading