前言
無論是哪種 Web UI
框架都不可避免的要與 Svg
打交道,那么批量引入才更方便管理 Svg
。
創(chuàng)建React + Typescript項(xiàng)目
npx create-react-app my-ts-app --template typescript
通過require.context實(shí)現(xiàn)批量引入Svg
// src/assets/icons/index.ts
const requireAll = (requireContext: __WebpackModuleApi.RequireContext) => requireContext.keys().map(requireContext)
const icons = require.context('./', false, /\.svg$/)
requireAll(icons)
export {}
安裝@types/webpack-env解決類型報(bào)錯(cuò)
npm install --save @types/webpack-env
安裝craco,覆蓋React原有的webpack配置文件
npm i -D @craco/craco @craco/types
修改package.json腳本快捷方式為craco啟動(dòng)項(xiàng)目
"scripts": {
- "start": "react-scripts start"
+ "start": "craco start"
- "build": "react-scripts build"
+ "build": "craco build"
- "test": "react-scripts test"
+ "test": "craco test"
}
安裝svg-sprite-loader生成Svg雪碧圖
npm install svg-sprite-loader -D
安裝svgo-loader去除Svg的fill和stroke屬性
npm install svgo-loader --save-dev
新增craco.config.js配置文件
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
},
}
}
封裝Icon組件應(yīng)用Svg圖標(biāo)
// 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;
}
在index.tsx入口文件中引入批量引入Svg的函數(shù)
// src/index.tsx
import '@/assets/icons/index';
在App.tsx中引入Icon組件并應(yīng)用
// 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;
修改tsconfig.json新增別名@解決報(bào)錯(cuò)
{
"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"
]
}
啟動(dòng)項(xiàng)目,目錄結(jié)構(gòu)如下
文章來源:http://www.zghlxwxcb.cn/news/detail-846198.html
文章來源地址http://www.zghlxwxcb.cn/news/detail-846198.html
參考
- https://ryanhutzley.medium.com/dynamic-svg-imports-in-create-react-app-d6d411f6d6c6
- https://github.com/airbnb/babel-plugin-inline-react-svg/issues/51
- https://blog.shianqi.com/2017/12/13/Webpack/SVG-sprite/
- https://pganalyze.com/blog/building-svg-components-in-react
- https://juejin.cn/post/6844904194747400199
- https://blog.csdn.net/qq_44883318/article/details/132202175
- https://juejin.cn/post/7035808121272893477
- https://github.com/dilanx/craco/issues/395
- https://segmentfault.com/a/1190000023807589
- https://blog.csdn.net/qq_39953537/article/details/93760188
- https://juejin.cn/post/7207336474150273061
- https://juejin.cn/post/6918723151732391950#heading-0
- https://juejin.cn/post/6981836039463632932
- https://segmentfault.com/a/1190000039850941
總結(jié)
- 配置別名需要tsconfig.json和craco.config.js一起配合
- 批量引入組件或者資源通過require.context函數(shù)實(shí)現(xiàn)
- module css實(shí)現(xiàn)組件的私有樣式,相當(dāng)于Vue中 scoped 作用域
到了這里,關(guān)于【React】React18+Typescript+craco配置最小化批量引入Svg并應(yīng)用的組件的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!