# Icon Component

# SetUp

We define a <Icon /> tag as our icon component's name. name property determines what the icon looks like.
Firstly, we declared function type and props type. Here are codes in Icon.tsx:

import React from "react";
interface IconProps {
  name: string;
}
const Icon: React.FunctionComponent<IconProps> = (props) => {
  return (
    <svg>
      <use xlinkHref={`#${props.name}`}</use>
    </svg>
  )
}

export default Icon
1
2
3
4
5
6
7
8
9
10
11
12
13

Use Icon component in Index.tsx:

<Icon name="wechat" />
1

# svg-sprite-loader

Here we use svg format to display icons.

# 1. Run yarn add svg-sprite-loader --dev

# 2. Edit webpack.config.js:

{
  test: /icons.+\.svg$/,
  loader: 'svg-sprite-loader',
},
1
2
3
4

# 3. Make .tsx recognize .svg

# create a folder that named types and create a custom.d.ts:

declare module "*.svg" {
  const content: any;
  export default content;
}
1
2
3
4

# edit tsconfig.json:

"include": [
  "lib/**/*" //types folder is in it so that omit
 ],
1
2
3

# ImportAll: Dynamic Loading

In some cases, We want to import dozens of icons from icons folder. In old way, we would add them one by one by using import syntax which produce redundant codes and we don't want it obviously. You can feel free to fix this issue if you adopt dynamic loading:

let importAll = requireContext => requireContext.keys().forEach(requireContext);
try {
  importAll(require.context("./icons/", true, /\.svg$/));
} catch (error) {
  console.log(error);
}
1
2
3
4
5
6

# Tree Shaking: Static Loading

In the above codes, dynamic loading has some cons. one of them is that losing tree shaking functionality. For a metaphor, many dependencies are fruits in the tree, Once step into compiling, static compiling will remove some dependencies that never used. it's feels like shaking an apple tree. It aims to descend the amount of dependencies to make it flexible and lightweight. But dynamic loading doesn't have this feature. So it shouldn't be abused arbitrarily.