背景
我们有个sdk库,现在要实现一个截屏方法供h5和rn使用。由于不能走一套代码所以需要分开写俩文件,但是导出的时候希望一致这样方便开发者;
// 开发者
import {createPoster} from 'wb-taro/src/CreatePoster';
// 组件目录结构
CreatePoster/h5.ts
CreatePoster/rn.ts
CreatePoster/index.ts
我们内部根据环境判断是那个环境,就引用对应的文件即可;
过程
感觉easy啊
if(process.env.TARO_ENV === "rn"){
export {createPoster } from './rn'
}else{
export {createPoster } from './h5'
}
看起来没毛病,先引入再直接导出。但是!!!
esmodule是编译时解析的,环境判断是在进行时的,所以这if写的没啥用;
另外导出声明只能在模块中使用不能包裹在 if 中!
失败!!!
esmodule编译时解析,那么我们换成common规范呢?
if(process.env.TARO_ENV === "rn"){
module.exports = require('./rn')
}else{
module.exports = require('./h5')
}
}
引用并调用,结果符合预期顺利执行拿到结果~~
import {createPoster} from 'wb-taro/src/CreatePoster';
createPoster({
viewTag:'#bePost',
clickBtnCb:(res)=>{
console.log(`${res} click!!`)
}
})
但是!!!定睛一看
怎么还红线了呢?!什么情况!?!?
不是一个模块不是一个模块????
好吧,,
import
一个common
模块确实会标红,要不直接吧import
改成require
?不太好,,毕竟页面其他sdk方法都是用的import
引入的。
那这怎么搞呢?
结论
直接上结论,先全部导入之后重命名!
import {createPoster as H5 } from './h5'
import {createPoster as RN } from './rn'
const final = process.env.TARO_ENV === "rn" ? RN : H5
export {
final as createPoster
}
使用中间变量过度,这样静态编译的时候就可以拿到RN
和H5
,由于声明了final
我们 export
也没啥问题~
当process.env.TARO_ENV
环境变量是h5
时, 也只会将import {createPoster as H5 } from './h5'
的H5
打包进去,RN这部分会被treeshake掉。