Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Redux Support #93

Merged
merged 20 commits into from
Apr 15, 2017
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 10 additions & 8 deletions packages/wepy-cli/src/compile-script.js
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,7 @@ export default {
},

npmHack (filename, code) {
code = code.replace(/process\.env\.NODE_ENV/g, JSON.stringify(process.env.NODE_ENV));
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这一句是处理哪里的内容的呢?能否加个注释。

switch(filename) {
case 'lodash.js':
case '_global.js':
Expand All @@ -141,6 +142,8 @@ export default {
// IOS 1.10.2 Promise BUG
code = code.replace('Promise && Promise.resolve', 'false && Promise && Promise.resolve');
break;
case '_freeGlobal.js':
code = code.replace('module.exports = freeGlobal;', 'module.exports = freeGlobal || this;')
}
return code;
},
Expand Down Expand Up @@ -172,20 +175,19 @@ export default {
}
if (type !== 'npm') {
if (type === 'page' || type === 'app') {
let defaultExport = 'exports.default';
let matchs = code.match(/exports\.default\s*=\s*(\w+);/i);
if (matchs) {
defaultExport = matchs[1];
code = code.replace(/exports\.default\s*=\s*(\w+);/i, '');
code = code.replace(/exports\.default\s*=\s*(\w+);/ig, function (m, defaultExport) {
if (defaultExport === 'undefined') {
return '';
}

if (type === 'page') {
let pagePath = path.join(path.relative(appPath.dir, opath.dir), opath.name).replace(/\\/ig, '/');
code += `\nPage(require('wepy').default.$createPage(${defaultExport} , '${pagePath}'));\n`;
return `\nPage(require('wepy').default.$createPage(${defaultExport} , '${pagePath}'));\n`;
} else {
appPath = opath;
code += `\nApp(require('wepy').default.$createApp(${defaultExport}));\n`;
return `\nApp(require('wepy').default.$createApp(${defaultExport}));\n`;
}
}
});
}
}

Expand Down
2 changes: 1 addition & 1 deletion packages/wepy-cli/src/compile-template.js
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ export default {
return matchs.replace(/[^\.\w'"]([a-z_\$][\w\d\._\$]*)/ig, (match, word, n) => {
//console.log(matchs + '------' + match + '--' + word + '--' + n);
let char = match[0];
let tmp = word.match(/^(\w+)(.*)/);
let tmp = word.match(/^([\w$]+)(.*)/);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这里是 $ ?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

因为对 redux 处理中默认加入了 $state 这个 computed 的值方便直接使用。
而且加上 $ 也是合理的吧,毕竟从变量上来说是可以有$的

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

对,所以是\s, 上面的comment竟然被转义了

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这个是在 [] 中的,应该不用转义就好

let w = tmp[1];
let rest = tmp[2];
if (ignores[w] || this.isInQuote(matchs, n)) {
Expand Down
4 changes: 2 additions & 2 deletions packages/wepy-cli/src/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -353,8 +353,8 @@ const utils = {
dir = opath.dir.replace('node_modules', `${dist}${path.sep}npm`) + path.sep;
} else {
let currentPath = path.relative(this.currentDir + path.sep + src, opath.dir);
dir = path.join(this.currentDir, dist, currentPath);
//dir = (opath.dir + path.sep).replace(path.sep + src + path.sep, path.sep + dist + path.sep);
dir = path.join(this.currentDir, dist, currentPath, path.sep);
// dir = (opath.dir + path.sep).replace(path.sep + src + path.sep, path.sep + dist + path.sep);
}
return dir + opath.name + ext;
},
Expand Down
30 changes: 29 additions & 1 deletion packages/wepy-cli/src/wepy.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ let generateProject = (name, config) => {

let template = config.empty ? emptyDir : templateDir;

const useRedux = !config.empty && config.redux;

let pkg = path.join(template, 'package.json');
pkg = util.readFile(pkg);
pkg = JSON.parse(pkg);
Expand All @@ -54,6 +56,7 @@ let generateProject = (name, config) => {
];
const devDependencies = [
'wepy-compiler-babel',
'babel-plugin-transform-decorators-legacy',
'babel-plugin-syntax-export-extensions',
'babel-plugin-transform-export-extensions',
'babel-preset-es2015',
Expand All @@ -67,15 +70,24 @@ let generateProject = (name, config) => {
'eslint-config-standard@7.1.0',
'eslint-friendly-formatter@2.0.7',
'eslint-plugin-html@2.0.1',
'eslint-plugin-promise@2.0.1',
'eslint-plugin-promise@3.5.0',
'eslint-plugin-standard@2.0.1',
'wepy-eslint'
];
const reduxDeps = [
'redux',
'wepy-redux',
'redux-promise',
'redux-actions'
];

if (!config.empty) {
dependencies.push('wepy-com-toast');
dependencies.push('wepy-async-function');
}
if (useRedux) {
dependencies.push.apply(dependencies, reduxDeps);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

dependencies = dependencies.concat(reduxDeps)

}

if (config.lint) {
devDependencies.push.apply(devDependencies, eslintDeps);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

同上

Expand All @@ -94,6 +106,21 @@ let generateProject = (name, config) => {
// --on-lint will not copy eslint config
if (['.editorconfig', '.eslintignore', '.eslintrc'].indexOf(file) !== -1 && !config.lint)
return;
// 只有 redux 的项目拷贝 redux 相关内容 且做替换
const unReduxFiles = ['src/app.wpy', 'src/components/counter.wpy'];
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

在非--redux模式下,生成的template中并没有排除 redux 模式的相关文件,这样会导致普通模式下文件再次build报错。

const reduxFiles = ['src/app-redux.wpy', 'src/components/counter-redux.wpy'];
const index = reduxFiles.indexOf(file);
if (useRedux) {
if (unReduxFiles.indexOf(file) !== -1) {
return;
}
// 将 reduxFiles 的文件重新命名
if (index >= 0) {
target = path.join(util.currentDir, unReduxFiles[index]);
}
} else if (index !== -1 || file.indexOf('src/store/') === 0) {
return;
}
if (file === 'wepy.config.js') {
if (!config.lint) {
// 去掉 eslint: true,
Expand Down Expand Up @@ -221,6 +248,7 @@ commander.option('-f, --file <file>', '待编译wpy文件');
commander.option('--no-cache', '对于引用到的文件,即使无改动也会再次编译');
commander.option('--empty', '使用new生成项目时,生成空项目内容');
commander.option('--no-lint', '使用new生成项目时,禁用eslint');
commander.option('--redux', '使用new生成项目时,增加redux相关内容');
commander.option('-w, --watch', '监听文件改动');

commander.command('build').description('编译项目').action(projectPath => {
Expand Down
73 changes: 73 additions & 0 deletions packages/wepy-cli/templates/template/src/app-redux.wpy
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
<style lang="less">
.container {
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: space-between;
box-sizing: border-box;
}
</style>

<script>
import wepy from 'wepy'
import 'wepy-async-function'
import { setStore } from 'wepy-redux'
import configStore from './store'

const store = configStore()
setStore(store)

export default class extends wepy.app {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

示例不够充分,目前只有一个counter组件使用了redux。需要再加入一个组件,看不同组件中的同一数据流是否存在问题。

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这个在我的原始demo是有的,但后来我思考的是 counter 是多个实例的,所以也算是“多”个组件了

config = {
pages: [
'pages/index'
],
window: {
backgroundTextStyle: 'light',
navigationBarBackgroundColor: '#fff',
navigationBarTitleText: 'WeChat',
navigationBarTextStyle: 'black'
}
}

globalData = {
userInfo: null
}

constructor () {
super()
this.use('requestfix')
}

onLaunch() {
this.testAsync()
}

sleep (s) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('promise resolved')
}, s * 1000)
})
}

async testAsync () {
const data = await this.sleep(3)
console.log(data)
}

getUserInfo(cb) {
const that = this
if (this.globalData.userInfo) {
return this.globalData.userInfo
}
wepy.getUserInfo({
success (res) {
that.globalData.userInfo = res.userInfo
cb && cb(res.userInfo)
}
})
}
}
</script>
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
<style lang="less">
.counter {
text-align: left;
font-size: 12px;
}
.count {
font-size: 18px;
font-weight: bold;
}
</style>
<template>
<view class="counter {{style}}">
<button @tap="plus" size="mini"> + </button>
<button @tap="minus" size="mini"> - </button>
<button @tap="incNum" size="mini"> INCREMENT </button>
<button @tap="decNum" size="mini"> DECREMENT </button>
<button @tap="asyncInc" size="mini"> ASYNC INCREMENT </button>
<text class="count"> {{num}} </text>
<text class="count"> {{stateNum}} </text>
<text class="count"> {{asyncNum}} </text>
</view>
</template>
<script>
import wepy from 'wepy'
import { connect } from 'wepy-redux'
import { INCREMENT, DECREMENT } from '../store/types/counter'
import { asyncInc } from '../store/actions'

@connect({
stateNum (state) {
return state.counter.num
},
asyncNum (state) {
return state.counter.asyncNum
}
}, {
incNum: INCREMENT,
decNum: DECREMENT,
asyncInc
})
export default class Counter extends wepy.component {
props = {
num: {
type: [Number, String],
coerce: function (v) {
return +v
},
default: 50
}
}

data = {
}
events = {
'index-broadcast': (...args) => {
let $event = args[args.length - 1]
console.log(`${this.$name} receive ${$event.name} from ${$event.source.$name}`)
}
}

methods = {
plus () {
this.num = this.num + 1
console.log(this.$name + ' plus tap')

this.$emit('index-emit', 1, 2, 3)
},
minus () {
this.num = this.num - 1
console.log(this.$name + ' minus tap')
}
}
}
</script>
10 changes: 10 additions & 0 deletions packages/wepy-cli/templates/template/src/store/actions/counter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { ASYNC_INCREMENT } from '../types/counter'
import { createAction } from 'redux-actions'

export const asyncInc = createAction(ASYNC_INCREMENT, () => {
return new Promise(resolve => {
setTimeout(() => {
resolve(1)
}, 1000)
})
})
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './counter'
8 changes: 8 additions & 0 deletions packages/wepy-cli/templates/template/src/store/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { createStore, applyMiddleware } from 'redux'
import promiseMiddleware from 'redux-promise'
import rootReducer from './reducers'

export default function configStore () {
const store = createStore(rootReducer, applyMiddleware(promiseMiddleware))
return store
}
27 changes: 27 additions & 0 deletions packages/wepy-cli/templates/template/src/store/reducers/counter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { INCREMENT, DECREMENT, ASYNC_INCREMENT } from '../types/counter'

function counter (state = {num: 0, asyncNum: 0}, action) {
switch (action.type) {
case INCREMENT:
return {
...state,
num: state.num + 1
}
case DECREMENT:
return {
...state,
num: state.num - 1
}
case ASYNC_INCREMENT:
return {
...state,
asyncNum: state.asyncNum + action.payload
}
default:
return {
...state
}
}
}

export default counter
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { combineReducers } from 'redux'
import counter from './counter'

export default combineReducers({
counter
})
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export const INCREMENT = 'INCREMENT'

export const DECREMENT = 'DECREMENT'

export const ASYNC_INCREMENT = 'ASYNC_INCREMENT'
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './counter'
1 change: 1 addition & 0 deletions packages/wepy-cli/templates/template/wepy.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ module.exports = {
'stage-1'
],
plugins: [
'transform-decorators-legacy',
'transform-export-extensions',
'syntax-export-extensions'
]
Expand Down
Loading