小程序CSS-JS Shared variable,共享变量,减少CDN文件路径变量重复定义
CSS变量与JS共享: CSS Module的:export方法,功能上类似ES6的export关键字,即导出一个变量对象
首先定义一份sass文件如下:
$COMMON_ARROW_RIGHT: 'https://you.domain.com/123dfdds768fkasfhja3.png';
$INDEX_OLD: 'https://you.domain.com/s7812312312dsvasty8jkassd.png';
$MINE_USER_AVATAR: 'https://you.domain.com/79jksadsuek32423saasfh4.png';
//
:export {
COMMON_ARROW_RIGHT: $COMMON_ARROW_RIGHT;
INDEX_OLD: $INDEX_OLD;
MINE_USER_AVATAR: $SERVICE_WARNING;
}
然后定义cloud.js文件如下:
/**
* CDN,图片云,资源云,CSS-JS 变量共享
*/
import urls from './index.module.scss';
const clouds = {};
for(let i in urls) clouds[i] = urls[i].split('"')[1];
export default clouds;
CSS中使用
[@import](/user/import) "~[@cloud](/user/cloud)/index.module.scss";
.container {
position: relative;
width: 100%;
height: 100vh;
background: #f3f7f9 url($INDEX_OLD) top center no-repeat;
}
JS中使用:
JS中使用:
import Clouds from '[@cloud](/user/cloud)/index';
const { MINE_USER_AVATAR } = Clouds;
// Render函数部分伪代码:
<Image className={'global-user-avatar'} src={MINE_USER_AVATAR} />