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 all 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
20 changes: 12 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,9 @@ export default {
},

npmHack (filename, code) {
// 一些库(redux等) 可能会依赖 process.env.NODE_ENV 进行逻辑判断
// 这里在编译这一步直接做替换 否则报错
code = code.replace(/process\.env\.NODE_ENV/g, JSON.stringify(process.env.NODE_ENV));
switch(filename) {
case 'lodash.js':
case '_global.js':
Expand All @@ -141,6 +144,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 +177,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\$]+)(.*)/);
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
48 changes: 44 additions & 4 deletions 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 @@ -52,8 +54,9 @@ let generateProject = (name, config) => {
let dependencies = [
'wepy'
];
const devDependencies = [
let 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,18 +70,28 @@ 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) {
// concat more faster than push.apply
dependencies = dependencies.concat(reduxDeps);
}

if (config.lint) {
devDependencies.push.apply(devDependencies, eslintDeps);
devDependencies = devDependencies.concat(eslintDeps);
}

util.writeFile(packagePath, JSON.stringify(pkg));
Expand All @@ -89,11 +102,37 @@ let generateProject = (name, config) => {
const copyFn = function (sourcePath) {
return function (file) {
let target = path.join(util.currentDir, file);
let fileContent = util.readFile(path.join(sourcePath, file));

// --on-lint will not copy eslint config
if (['.editorconfig', '.eslintignore', '.eslintrc'].indexOf(file) !== -1 && !config.lint)
return;

// 只有 redux 的项目拷贝 redux 相关内容 且做替换
const unReduxFiles = [
path.join('src', 'app.wpy'),
path.join('src', 'pages', 'index.wpy'),
path.join('src' , 'components', 'counter.wpy')
];
const reduxFiles = [
path.join('src', 'app-redux.wpy'),
path.join('src', 'pages', 'index-redux.wpy'),
path.join('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(path.join('src', 'store')) === 0) {
// 同样排除 store 内容
return;
}

let fileContent = util.readFile(path.join(sourcePath, file));
if (file === 'wepy.config.js') {
if (!config.lint) {
// 去掉 eslint: true,
Expand Down Expand Up @@ -221,6 +260,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>
Loading