美文网首页
条件判断动态引入esmodule模块

条件判断动态引入esmodule模块

作者: 薯条你哪里跑 | 来源:发表于2023-08-17 17:08 被阅读0次

背景

我们有个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
}

使用中间变量过度,这样静态编译的时候就可以拿到RNH5,由于声明了final 我们 export也没啥问题~
process.env.TARO_ENV环境变量是h5时, 也只会将import {createPoster as H5 } from './h5'H5打包进去,RN这部分会被treeshake掉。

相关文章

网友评论

      本文标题:条件判断动态引入esmodule模块

      本文链接:https://www.haomeiwen.com/subject/xtcrmdtx.html