watermark.wxml
- <view class="water_top" style="pointer-events: none;">
- <view class="water-text">{{watermarkText}}view>
- <view class="water-text">{{watermarkText}}view>
- <view class="water-text">{{watermarkText}}view>
- <view class="water-text">{{watermarkText}}view>
- <view class="water-text">{{watermarkText}}view>
- <view class="water-text">{{watermarkText}}view>
- <view class="water-text">{{watermarkText}}view>
- <view class="water-text">{{watermarkText}}view>
- <view class="water-text">{{watermarkText}}view>
- view>
watermark.wxss
- .water_top{
- position: fixed;
- top:0;
- bottom: 0;
- left: 0;
- right: 0;
- transform:rotate(-12deg); /** 旋转 可自己调整 **/
- z-index: 9999;
- }
- .water-text{
- float: left;
- width:375rpx;
- color: rgba(169,169,169,.1); //文字颜色
- text-align: center;
- font-size: 95%;
- margin: 100rpx 0; /** 间距 可自调 **/
- }
watermark.js
- // components/watermark/watermark.js
- import { getUserInfo } from "../../api/api"
- Component({
- /**
- * 组件的属性列表
- */
- properties: {
- name:String
- },
-
- /**
- * 组件的初始数据
- */
- data: {
- watermarkText:'测试'
- },
-
- /**
- * 组件生命周期声明对象,组件的生命周期
- * :created、attached、ready、moved、detached
- * 将收归到 lifetimes 字段内进行声明
- * 原有声明方式仍旧有效,如同时存在两种声明方式
- * 则 lifetimes 字段内声明方式优先级最高
- */
- lifetimes:{
- ready(){
- this.getUserInfo();
- }
- },
-
- /**
- * 组件的方法列表
- */
- methods: {
- getUserInfo(){
- getUserInfo().then(res=>{
- this.setData({
- watermarkText: res.data?.name
- })
- }).catch(err=>{
- wx.showToast({
- title: err.data,
- icon: 'none'
- })
- })
- }
-
- }
- })
-
- {
- ...
- "usingComponents": {
- "watermark":"./components/watermark/watermark"
- }
- }
-
- <watermark name="班长">watermark>
新建文件generator/index.js
代码如下
- /**
- * @description: 将组件插入到小程序项目,包括app.json和page
- * @param {string} cpName 组件名
- * @param {string} cpPath 组件路径
- * @param {string} cpString 要插入的组件字符串内容
- * @param {Array
} whiteList 不需要插入的组件 - * @return {*}
- */
- function insertComponent(
- cpName = 'watermark',
- cpPath = '/components/watermark/watermark',
- cpString = `
`, - whiteList = []
- ) {
- try {
- const path = require('path');
- const fs = require('fs');
- const entryFilePath = './app.json';
-
- if (fs.statSync(entryFilePath)) {
- const { EOL } = require('os');
-
- // app.json 内容
- const contentMain = fs.readFileSync(path.resolve(entryFilePath), {
- encoding: 'utf-8',
- });
- // 获取每行内容
- const contentMainLine = contentMain.split(/\r?\n/g);
- // 组件('new-user-dialog':)正则
- const compReg = eval(`/['"]?${cpName}['"]?:/`);
- // 组件正则
- const usingComponentReg = /['"]?usingComponents['"]?:/;
- // 检测组件配置项所在行
- const ucLineNum = contentMainLine.findIndex(line =>
- line.match(usingComponentReg)
- );
-
- // TODO: 插入组件部分
- // 检测tabbar
- const tabBarStartReg = /['"]?tabBar['"]?:/;
- // app.json没有配置自定义组件,自定义添加
- if (!compReg.test(contentMain)) {
- // 如果没有usingComponent配置项的话,就找tabbar,放在后面
- if (ucLineNum < 0) {
- const tabBarLineNum = contentMainLine.findIndex(line =>
- line.match(tabBarStartReg)
- );
- contentMainLine[
- tabBarLineNum - 1
- ] += `${EOL} "usingComponents": { "${cpName}": "${cpPath}" },`;
- } else {
- // 有配置项,放到配置项里面
- contentMainLine[ucLineNum] += `${EOL} "${cpName}": "${cpPath}",`;
- }
- fs.writeFileSync(
- path.resolve(entryFilePath),
- contentMainLine.join(EOL),
- { encoding: 'utf-8' }
- );
- }
-
- // TODO: 插入page部分
- // pages开始,逗号结尾的部分
- const pageConfigReg = /['"]?pages['"]?: \[([^\]]+)\],/;
- // 将pages按照逗号分隔为数组
- const pageList = pageConfigReg
- .exec(contentMain)[1]
- .replace(/\s+/g, '')
- .replace(/"/g, '')
- .replace(/\n\s+/g, '')
- .split(',')
- .filter(pn => {
- return !whiteList.includes(pn);
- });
- pageList.forEach(pagePath => {
- insertFileToPage(pagePath, cpString);
- });
- }
- } catch (error) {
- console.warn(error);
- }
- }
-
- /**
- * @description: 将组件插入到page
- * @param {string} pagePath 组件page路径
- * @param {string} cpString 要插入的组件字符串内容
- * @return {*}
- */
- function insertFileToPage(pagePath, cpString) {
- const path = require('path');
- const fs = require('fs');
- if (pagePath.indexOf('wxml' < 0)) {
- pagePath += '.wxml';
- }
- const pageContent = fs.readFileSync(path.resolve(pagePath), {
- encoding: 'utf-8',
- });
- // 组件('new-user-dialog':)正则
- const compReg = new RegExp(cpString);
-
- // 没有引用标签则添加标签引用
- if (!compReg.test(pageContent)) {
- const { EOL } = require('os');
- const pageLine = pageContent.split(/\r?\n/g);
- // 添加到最后一行
- pageLine[pageLine.length - 1] += `${EOL}${cpString}`;
- fs.writeFileSync(path.resolve(pagePath), pageLine.join(EOL), {
- encoding: 'utf-8',
- });
- }
- }
-
- /**
- * @description: 将组件插入到小程序项目,包括app.json和page
- * @param {string} cpName 组件名
- * @param {string} cpPath 组件路径
- * @param {string} cpString 要插入的组件字符串内容
- * @param {Array
} whiteList 不需要插入的组件 - * @return {*}
- */
- function deleteComponent(
- cpName = 'new-user-dialog',
- cpPath = '/components/newUserDialog/newUserDialog',
- cpString = `
`, - whiteList = [
- 'pages/mine/login/logout/logut',
- 'pages/mine/login/method/method',
- 'pages/mine/login/scan/scan',
- 'pages/mine/login/people/people',
- 'pages/mine/collect/collect',
- ]
- ) {
- try {
- const path = require('path');
- const fs = require('fs');
- const entryFilePath = './app.json';
-
- if (fs.statSync(entryFilePath)) {
- // app.json 内容
- const contentMain = fs.readFileSync(path.resolve(entryFilePath), {
- encoding: 'utf-8',
- });
- // pages开始,逗号结尾的部分
- const pageConfigReg = /['"]?pages['"]?: \[([^\]]+)\],/;
- // 将pages按照逗号分隔为数组
- const pageList = pageConfigReg
- .exec(contentMain)[1]
- .replace(/\s+/g, '')
- .replace(/"/g, '')
- .replace(/\n\s+/g, '')
- .split(',')
- .filter(pn => {
- return !whiteList.includes(pn);
- });
- pageList.forEach(pagePath => {
- deleteFileToPage(pagePath, cpString);
- });
- }
- } catch (error) {
- console.warn(error);
- }
- }
-
- /**
- * @description: 将组件从page中删除
- * @param {string} pagePath 组件page路径
- * @param {string} cpString 要删除的组件字符串内容
- * @return {*}
- */
- function deleteFileToPage(pagePath, cpString) {
- const path = require('path');
- const fs = require('fs');
- if (pagePath.indexOf('wxml' < 0)) {
- pagePath += '.wxml';
- }
- let pageContent = fs.readFileSync(path.resolve(pagePath), {
- encoding: 'utf-8',
- });
- // 组件('new-user-dialog':)正则
- const compReg = new RegExp(cpString, 'g');
-
- // 有引用标签则删除标签引用
- if (compReg.test(pageContent)) {
- pageContent = pageContent.replace(compReg, '');
- fs.writeFileSync(path.resolve(pagePath), pageContent, {
- encoding: 'utf-8',
- });
- }
- }
-
- // deleteComponent()
- insertComponent();
-
在使用命令工具内输入:
node .\generator\index.js
即可实现
小程序全局组件使用(自动插入节点)_路不周以左转兮的博客-CSDN博客_小程序添加节点