Code Monkey home page Code Monkey logo

react-native-iconfont-cli's Introduction

react-native-iconfont-cli

用纯JS把iconfont.cn的图标转换成RN组件,不依赖字体,支持多色彩,支持热更新

痛点

通常地,当我们想在RN里使用iconfont,我们可能会借助react-native-vector-icons导入ttf字体文件,或者直接手动下载各个svg文件到本地,然后单个使用。

使用ttf字体有一个弊端,就是每次更新图标,都要相应的更新ttf文件,然后再次打包发布APP。而且ttf不支持多种色彩的图标,导致所有图标都是单色。如果你是借助react-native-vector-icons,该库内置了10多套ttf文件,合起来有2M左右;你可能用不到它们,但是它们仍然会被打包进你的APP里。

下载svg到本地也不方便,因为你需要额外维护一份图标字体,有可能造成线上和本地的图标不一致问题。而且如果你想动态地改变svg的渲染色彩,基本上是不可能的,只能渲染原图的颜色。


为了解决这些问题,我用纯Javascript实现iconfont到React组件的转换操作,不需要依赖ttf字体文件,不需要手动下载图标到本地。

特性

1、纯组件,不依赖字体,体积小
2、支持渲染多色彩图标,支持自定义颜色
3、支持热更新
4、自动化生成图标组件,支持es6和typescript两种文件格式

Step 1

安装插件

# Yarn
yarn add react-native-svg
yarn add react-native-iconfont-cli --dev

# Npm
npm install react-native-svg
npm install react-native-iconfont-cli --save-dev

Step 2

静态链接。请注意您使用的React-Native版本号

# RN < 0.60
react-native link react-native-svg

# RN >= 0.60
cd ios && pod install

Step 3

生成配置文件

npx iconfont-init

此时项目根目录会生成一个iconfont.json的文件,内容如下:

{
    "symbol_url": "请参考README.md,复制官网提供的JS链接",
    "use_typescript": false,
    "save_dir": "./src/iconfont",
    "trim_icon_prefix": "icon",
    "default_icon_size": 18,
    "local_svgs": "./localSvgs"
}

配置参数说明:

symbol_url

请直接复制iconfont官网提供的项目链接。请务必看清是.js后缀而不是.css后缀。如果你现在还没有创建iconfont的仓库,那么可以填入这个链接去测试:http://at.alicdn.com/t/font_1373348_ghk94ooopqr.js


use_typescript

如果您的项目使用Typescript编写,请设置为true。这个选项将决定生成的图标组件是.tsx还是.js后缀。

当该值为false时,我们会为您的图标生成.js.d.ts两种文件,以便您能享受到最好的开发体验。

save_dir

根据iconfont图标生成的组件存放的位置。每次生成组件之前,该文件夹都会被清空。

trim_icon_prefix

如果你的图标有通用的前缀,而你在使用的时候又不想重复去写,那么可以通过这种配置这个选项把前缀统一去掉。

default_icon_size

我们将为每个生成的图标组件加入默认的字体大小,当然,你也可以通过传入props的方式改变这个size值。

local_svgs

本地 svg 的路径, 配置此项后在路径中添加 svg 文件即可。支持渐变图标(iconfont官网不能上传渐变图标)。

注 1: 暂不支持 color 参数
注 2: 如果启用该功能,请确保react-native-svg的版本>=9.13.0

Step 4

开始生成React-Native标准组件

npx iconfont-rn

生成后查看您设置的保存目录中是否含有所有的图标,你可以参考snapshots目录的快照文件,以区分不同模式下的图标结构。

使用


现在我们提供了两种引入方式供您选择:

1、使用汇总Icon组件:

import IconFont from '../src/iconfont';

export const App = () => {
  return (
    <View>
      <IconFont name="alipay" size={20} />
      <IconFont name="wechat" />
    </View>
  );
};

2、使用单个图标。这样可以避免没用到的图标也打包进App:

import IconAlipay from '../src/iconfont/IconAlipay';
import IconWechat from '../src/iconfont/IconWechat';

export const App = () => {
  return (
    <View>
      <IconAlipay size={20} />
      <IconWechat />
    </View>
  );
};

图标尺寸

根据配置default_icon_size,每个图标都会有一个默认的尺寸,你可以随时覆盖。

<IconFont name="alipay" size={20} />

图标单色

单色图标,如果不指定颜色值,图标将渲染原本的颜色。如果你想设置为其他的颜色,那么设置一个你想要的颜色即可。

注意:如果你在props传入的color是字符串而不是数组,那么即使原本是多色彩的图标,也会变成单色图标。

<IconFont name="alipay" color="green" />

图标多色彩

多色彩的图标,如果不指定颜色值,图标将渲染原本的多色彩。如果你想设置为其他的颜色,那么设置一组你想要的颜色即可

<IconFont name="alipay" color={['green', 'orange']} />

颜色组的数量以及排序,需要根据当前图标的信息来确定。您需要进入图标组件中查看并得出结论。

更新图标

当您在iconfont.cn中的图标有变更时,只需更改配置symbol_url,然后再次执行Step 4即可生成最新的图标组件

# 修改 symbol_url 配置后执行:
npx iconfont-rn

欢迎使用,并给我一些反馈和建议,让这个库做的更好

react-native-iconfont-cli's People

Contributors

fwh1990 avatar grewer avatar lanceli avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-native-iconfont-cli's Issues

[patch-package] Using hash key for local icons instead of increasement key to prevent conflict

This patch issue is submitted by patch-package.

In my project I found that if more than one commit is adding local icon to project, the key of local icon will be conflict in a large scale. So I made this patch:

diff --git a/node_modules/react-native-iconfont-cli/libs/generateComponent.js b/node_modules/react-native-iconfont-cli/libs/generateComponent.js
index ddeae3b..6f5ee3f 100644
--- a/node_modules/react-native-iconfont-cli/libs/generateComponent.js
+++ b/node_modules/react-native-iconfont-cli/libs/generateComponent.js
@@ -12,10 +12,14 @@ var getTemplate_1 = require("./getTemplate");
 var replace_1 = require("./replace");
 var whitespace_1 = require("./whitespace");
 var copyTemplate_1 = require("./copyTemplate");
+var crypto = require('crypto')
 var SVG_MAP = {
     path: 'Path',
 };
 var ATTRIBUTE_FILL_MAP = ['path'];
+
+const sha1 = (data) => crypto.createHash("sha1").update(data, "binary").digest("hex");
+
 exports.generateComponent = function (data, localSvg, config) {
     var svgComponents = new Set();
     var names = [];
@@ -80,7 +84,6 @@ exports.generateComponent = function (data, localSvg, config) {
             typeDefinitionFile = replace_1.replaceComponentName(typeDefinitionFile, componentName);
             fs_1.default.writeFileSync(path_1.default.join(saveDir, componentName + '.d.ts'), typeDefinitionFile);
         }
         console.log(colors_1.default.green('√') + " Generated icon \"" + colors_1.default.yellow(iconId) + "\"");
     });
     /**
      * 本地文件添加
@@ -97,7 +100,7 @@ exports.generateComponent = function (data, localSvg, config) {
         names.push(name);
         cases += whitespace_1.whitespace(4) + "case '" + name + "':\n";
         imports.push(componentName);
-        cases += whitespace_1.whitespace(6) + "return <" + componentName + " key=\"L" + (index + 1) + "\" {...rest} />;\n";
+        cases += whitespace_1.whitespace(6) + "return <" + componentName + " key=\"L-" + sha1(componentName) + "\" {...rest} />;\n";
         singleFile = getTemplate_1.getTemplate('LocalSingleIcon' + jsxExtension);
         singleFile = replace_1.replaceSize(singleFile, config.default_icon_size);
         singleFile = replace_1.replaceSvgComponents(singleFile, currentSvgComponents);
@@ -110,7 +113,6 @@ exports.generateComponent = function (data, localSvg, config) {
             typeDefinitionFile = replace_1.replaceComponentName(typeDefinitionFile, componentName);
             fs_1.default.writeFileSync(path_1.default.join(saveDir, componentName + '.d.ts'), typeDefinitionFile);
         }
         console.log(colors_1.default.green('√') + " Generated local icon \"" + colors_1.default.yellow(name) + "\"");
     });
     var iconFile = getTemplate_1.getTemplate('Icon' + jsxExtension);
     iconFile = replace_1.replaceSize(iconFile, config.default_icon_size);

This issue body was partially generated by patch-package.

关于组件优化

正常生成的组件是这样:

const IconFont: FunctionComponent<Props> = ({ name, ...rest }) => {
  switch (name) {
    // 省略
  }

  return null;
};

不打算加一个 memo 来优化一下吗

const IconFont: FunctionComponent<Props> = React.memo(({ name, ...rest }) => {
  switch (name) {
    // 省略
  }

  return null;
});

color不起作用。

const xml = `
<svg t="1626763143756" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1958" xmlns:xlink="http://www.w3.org/1999/xlink" width="32" height="32"><defs><style type="text/css"></style></defs><path d="M836.664 302.486c17.528-17.184 45.666-16.906 62.85 0.622 17.184 17.528 16.906 45.666-0.622 62.85L536.226 721.514c-17.53 17.186-45.674 16.906-62.858-0.628L124.924 365.33c-17.18-17.53-16.896-45.67 0.634-62.85 17.532-17.18 45.672-16.896 62.852 0.634L505.74 626.92l330.924-324.434z" p-id="1959" fill="#2c2c2c"></path></svg>
`;

let IconDown: FunctionComponent<Props> = ({ size, color, ...rest }) => {
  return <SvgXml xml={xml} width={size} height={size} {...rest} />;
};

// 使用
<Iconfont name="down" color="#ff0000" size={px(18)} />

从表现上看,size起作用了,但是color不起作用,传进去红色,但是实际上显示的还是path的默认颜色。
有什么办法可以修改颜色吗?

eslint-disable 提示 warning

1:0 warning Unexpected unlimited 'eslint-disable' comment. Specify some rule names to disable eslint-comments/no-unlimited-disable
1:1 warning ESLint rules are disabled but never reported eslint-comments/no-unused-disable

优化 replaceImports 函数

Hi! 👋

Firstly, thanks for your work on this project! 🙂

Today I used patch-package to patch [email protected] for the project I'm working on.

Here is the diff that solved my problem:

diff --git a/node_modules/react-native-iconfont-cli/libs/replace.js b/node_modules/react-native-iconfont-cli/libs/replace.js
index 42c19e8..129d72a 100644
--- a/node_modules/react-native-iconfont-cli/libs/replace.js
+++ b/node_modules/react-native-iconfont-cli/libs/replace.js
@@ -28,7 +28,7 @@ exports.replaceSingleIconContent = function (content, render) {
     return content.replace(/#iconContent#/g, render);
 };
 exports.replaceImports = function (content, imports) {
-    return content.replace(/#imports#/g, imports.map(function (item) { return "import " + item + " from './" + item + "';"; }).join('\n'));
+    return content.replace(/#imports#/g, imports.map(function (item) { return "export { default as " + item + "} from './" + item + "';"; }).join('\n'));
 };
 exports.replaceHelper = function (content) {
     return content.replace(/#helper#/g, 'import { getIconColor } from \'./helper\';');

This issue body was partially generated by patch-package.

建议,全本地化svg处理

仅有本地svg需要处理时,也必须加入symbol_url,建议做成可选参数,只有本地svg时,也能直接使用这个插件

npx iconfont-init 出错 code E404

npm ERR! code E404
npm ERR! 404 Not Found - GET https://registry.npmjs.com/iconfont-init - Not found
npm ERR! 404
npm ERR! 404 'iconfont-init@latest' is not in the npm registry.
npm ERR! 404 You should bug the author to publish it (or use the name yourself!)
npm ERR! 404
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, http url, or git url.

文档描述不理解

在文档里有两处注解:
注 1: 暂不支持 color 参数
注 2: 如果启用该功能,请确保react-native-svg的版本>=9.13.0

如果启用该功能是指启用color参数吗?请问要如何启用?我react-native-svg 版本12.1.0,我把color参数传进去并不能生效,请问要做其它配置吗?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.