背景
最近需要在原有的小程序上进行新增页面,同时,相关页面未来可能需要支持h5访问。另外,我对小程序的开发也不太熟。看了小程序的文档,对小程序的代码写法也不太适应。在对比了目前比较流行的混合开发框架后,选择了Taro进行小程序的后续功能开发。
官方文档
查阅了Taro官方文档,找到以下相关的文档:
尝试一:原有小程序转Taro
刚开始被微信小程序转 Taro这个文档误导了,我选择先将现有代码使用taro convert
指令转成Taro代码,然后放入到新项目的src目录下。项目死活起不来,调试后发现是原项目引用了weui的组件,taro编译后,找不到相关组件了。原因是weui组件已经使用webpack打包过一次了,不是标准module,重新打包自然是找不到的。
weui无法支持非微信平台,现有的weui在未来肯定是要被干掉的,但是,我目前暂时只在小程序上使用,需要先将现有项目跑起来。只能使用第二种方案,两种代码混合开发了。
与小程序代码混写
查看官方文档,实在太简洁了。他的示例:
import Taro, { Component } from '@tarojs/taro'
import Index from './pages/index'
import './app.scss'
class App extends Component {
config = {
pages: [
'pages/index/index',
'pages/wxParse/wxParse',
'pages/echarts/echarts',
'pages/native/native'
],
window: {
backgroundTextStyle: 'light',
navigationBarBackgroundColor: '#fff',
navigationBarTitleText: 'WeChat',
navigationBarTextStyle: 'black'
}
}
componentDidMount () {}
componentDidShow () {}
componentDidHide () {}
componentCatchError () {}
render () {
return (
<Index />
)
}
}
Taro.render(<App />, document.getElementById('app'))
我需要将原有小程序代码中的App相关代码也迁移过来,然后入口页面是老的页面。 入口是老页面的话,死活想不通App中的render方法,要怎么把老页面的对象import进来。
后来看了方案一convert后的代码后,发现App中的render 完全可以return null
// 原App代码
@withWeapp({
globalData: {
xxx:null
},
onLaunch: function () {
console.log('[APP]Old onLaunch');
},
// 暴露给微信代码使用
store
})
class App extends Taro.Component {
config = {
pages: [
//'pages-taro/test/index',
"pages/xxx/xxx",
"pages/xxx/xxx2",
'pages-taro/xxx/xxx'
],
tabBar: {
color: '#656565',
selectedColor: '#FF4344',
list: [
{
pagePath: 'pages/xxx/xxx',
iconPath: './statics/img/home1.png',
selectedIconPath: './statics/img/home2.png',
text: '首页'
},
{
pagePath: 'pages/xxx/xxx',
iconPath: './statics/img/user1.png',
selectedIconPath: './statics/img/user2.png',
text: '我的'
}
]
},
window: {
backgroundTextStyle: 'light',
navigationBarBackgroundColor: '#fff',
navigationBarTitleText: 'WeChat',
navigationBarTextStyle: 'black'
},
style: 'v2',
sitemapLocation: 'sitemap.json'
};
render() {
return null;
}
} //app.js
Taro.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('app')
);
小程序原代码直接拷到src目录下面,即可。
运行后发现,statics下面的图片缺失。
修改config/index.js
文件,增加配置节:
copy: {
patterns: [
{
from: 'src/statics/img/',
to: 'dist/statics/img/'
},
{
from: 'sitemap.json',
to: 'dist/sitemap.json'
}
]
}
默认复制statics/img中的图片。使用Taro开发时,将图片放到另外一个文件夹下面,再import进来,防止引入不需要的图片。
现在老的小程序还可以继续使用,也可以调用getApp().store使用Taro下的redux。