npm创建uni-app项目时 依赖包内JS代码条件编译不生效 uni-app
npm创建uni-app项目时 依赖包内JS代码条件编译不生效 uni-app
开发环境 | 版本号 | 项目创建方式 |
---|---|---|
Mac | 10.13.6 | CLI |
示例代码:
npm包入口文件代码如下
// index.js
import store from './src/store/index'
export let CoreStore = store
npm包内store/index代码如下
// src/store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {user: {}},
actions: {
getUserInfo() {
/* #ifdef MP-ALIPAY */
console.log(11111111)
/* #endif */
/* #ifdef MP-WEIXIN */
console.log(22222222)
/* #endif */
/* #ifdef MP-TOUTIAO */
console.log(33333333)
/* #endif */
/* #ifdef MP-BAIDU */
console.log(44444444)
/* #endif */
/* #ifdef MP-QQ */
console.log(55555555)
/* #endif */
/* #ifdef H5 */
console.log(66666666)
/* #endif */
}
}
})
---
### 操作步骤:
#### 必现
```javascript
// main.js
import Vue from 'vue'
import App from './App'
import {CoreStore} from 'core-store'
Vue.config.productionTip = false
Vue.prototype.$store = CoreStore
Vue.store = CoreStore
CoreStore.dispatch('getUserInfo')
const app = new Vue({
...App,
store: CoreStore
})
app.$mount()
预期结果:
- 应该在对应平台只展示对应的数据内容
实际结果:
此时打印的结果为
11111111
22222222
33333333
44444444
55555555
66666666
更多关于npm创建uni-app项目时 依赖包内JS代码条件编译不生效 uni-app的实战教程也可以访问 https://www.itying.com/category-93-b0.html
3 回复
在 vue.config.js 中配置 transpileDependencies 显示转译你的依赖包
参考: https://cli.vuejs.org/zh/config/#transpiledependencies
更多关于npm创建uni-app项目时 依赖包内JS代码条件编译不生效 uni-app的实战教程也可以访问 https://www.itying.com/category-93-b0.html
可以了,感谢
在uni-app中使用npm包时,条件编译不生效是因为npm包中的代码没有被uni-app的编译器处理。uni-app的条件编译是在构建阶段由编译器处理的,而npm包中的代码是已经编译好的,不会再次经过uni-app的条件编译处理。
解决方法:
-
将需要条件编译的代码放在项目本地,而不是npm包中
-
如果必须放在npm包中,可以考虑以下方案:
- 使用环境变量区分平台
- 在运行时通过uni.getSystemInfoSync()判断平台
- 将不同平台的代码拆分为不同文件,在入口文件中动态引入
对于你的具体案例,建议修改store/index.js为:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const platformLog = {
'mp-alipay': () => console.log(11111111),
'mp-weixin': () => console.log(22222222),
// 其他平台...
}
const store = new Vuex.Store({
state: {user: {}},
actions: {
getUserInfo() {
const platform = uni.getSystemInfoSync().platform
platformLog[platform]?.()
}
}
})