ice-lab / ice-next

The repo was transferred to https://github.com/alibaba/ice
https://v3.ice.work/
MIT License
53 stars 7 forks source link

静态资源的导入方式 #666

Closed luhc228 closed 1 year ago

luhc228 commented 1 year ago

在 CSS 文件中引入静态资源

相对路径:

.container {
  background-image: url('@/assets/background.svg');
  background-image: url('../assets/background.svg');
}

url 引入:

.container {
    background-image: url('https://gw.alipayobjects.com/zos/rmsportal/TVYTbAXWheQpRcWDaDMu.svg')
}

在 JSX 中引入静态资源

在 public 目录中有静态资源:

return (
  <img src="/background.svg" />

  <div 
    style={{
      backgroundImage: 'url("/background.svg")',
      backgroundRepeat: 'no-repeat',
      backgroundPosition: 'center 110px',
      backgroundSize: '100%',
    }}
  />
)

url 引入:

return (
  <img src="https://gw.alipayobjects.com/zos/rmsportal/TVYTbAXWheQpRcWDaDMu.svg" />

  <div 
    style={{
      backgroundImage: 'url("https://gw.alipayobjects.com/zos/rmsportal/TVYTbAXWheQpRcWDaDMu.svg")',
      backgroundRepeat: 'no-repeat',
      backgroundPosition: 'center 110px',
      backgroundSize: '100%',
    }}
  />
)

import 的方式导入:

import background from '@/assets/background.svg';

return (
  <img src={background} />
)

使用 @svgr/webpack:

export default defineConfig({
  webpack(webpackConfig) {
    webpackConfig.module?.rules?.splice(7, 1, {
      test: /\.svg$/i,
      use: ['@svgr/webpack'],
    }); 
  }
})
import Icon from '@assets/icon.svg';

export default () => <Icon />

ssr 暂时不支持 @svgr/webpack

luhc228 commented 1 year ago
wssgcg1213 commented 1 year ago

666