赞
踩
无论是哪种 Web UI
框架都不可避免的要与 Svg
打交道,那么批量引入才更方便管理 Svg
。
npx create-react-app my-ts-app --template typescript
// src/assets/icons/index.ts
const requireAll = (requireContext: __WebpackModuleApi.RequireContext) => requireContext.keys().map(requireContext)
const icons = require.context('./', false, /\.svg$/)
requireAll(icons)
export {}
npm install --save @types/webpack-env
npm i -D @craco/craco @craco/types
"scripts": {
- "start": "react-scripts start"
+ "start": "craco start"
- "build": "react-scripts build"
+ "build": "craco build"
- "test": "react-scripts test"
+ "test": "craco test"
}
npm install svg-sprite-loader -D
npm install svgo-loader --save-dev
const path = require('path'); module.exports = { webpack: { alias: { '@': path.resolve(__dirname, 'src'), }, configure: (webpackConfig) => { const oneOfRule = webpackConfig.module.rules.find((rule) => rule.oneOf) if (oneOfRule) { oneOfRule.oneOf.splice(0, 0, { test: /\.svg$/, include: path.resolve(__dirname, "src/assets/icons"), use: [ { loader: 'svg-sprite-loader', options: { symbolId: "icon-[name]" } }, { loader: 'svgo-loader', options: { plugins: [ { name: 'removeAttrs', params: { attrs: '(fill|stroke)' } } ] } } ] }) } return webpackConfig }, } }
// src/components/Icon/index.tsx import React from "react"; import classes from './index.module.css' interface IconProps { name: string width: string height?: string fill?: string } const Icon = ({ name, width, height, fill }: IconProps) => { return ( <svg className={classes.icon} aria-hidden="true" width={width} height={height}> <use xlinkHref={'#icon-' + name} style={{color: fill}}></use> </svg> ) } export default Icon
/* src/components/Icon/index.module.css */
.icon {
vertical-align: -0.15em;
fill: currentColor;
overflow: hidden;
font-size: 0;
}
// src/index.tsx
import '@/assets/icons/index';
// src/App.tsx
import React from 'react';
import Icon from '@/components/Icon/index'
import './App.css';
function App() {
return (
<div className="App">
<Icon name='p_ding' width="30px" height='30px' fill="red" />
<Icon name='p_book' width="30px" height='30px' />
</div>
);
}
export default App;
{ "compilerOptions": { "target": "es5", "lib": [ "dom", "dom.iterable", "esnext" ], "allowJs": true, "skipLibCheck": true, "esModuleInterop": true, "allowSyntheticDefaultImports": true, "strict": true, "forceConsistentCasingInFileNames": true, "noFallthroughCasesInSwitch": true, "module": "esnext", "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, "jsx": "react-jsx", "baseUrl": "./src", "paths": { "@/*": ["./*"] } }, "include": [ "src" ] }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。