最近看了很多文章,發(fā)現(xiàn)都沒有很好的解釋如何搭建react環(huán)境并使用react-weui,以及webpack打包運(yùn)行中需要注意的問題點(diǎn)。下面我就基于當(dāng)前react-weui 1.1.3版本做一個(gè) 全面的入門教程。
1.下載 github最新源碼
下載地址:https://github.com/weui/react-weui
git clone 也行 下載 zip包也可以。
重點(diǎn)就是要看中間的這3個(gè)文件
package.json 編輯和運(yùn)行的腳步都在這個(gè)里面
webpack.config.js webpack打包配置文件
webpack.config.doc.js webpack打包配置文件(doc)
2.打開IDE 創(chuàng)建項(xiàng)目
ide采用webstrom, cmd用的是代替品cmder
下載地址:
webstrom:https://www.jetbrains.com/webstorm/
cmder:http://cmder.net/
3.初始化項(xiàng)目 加入npm包
這里使用 cnpm 代替npm
淘寶 NPM 鏡像 :https://npm.taobao.org/
你可以使用我們定制的 [cnpm](https://github.com/cnpm/cnpm) (gzip 壓縮支持) 命令行工具代替默認(rèn)的 npm:
$ npm install -g cnpm --registry=https://registry.npm.taobao.org
命令如下:
安裝項(xiàng)目?jī)?nèi)部的npm包
cnpm install
安裝相關(guān)的npm包
cnpm install --save react react-dom
cnpm install --save weui@1.1.0 react-weui
#這里一定要指明webpack版本 因?yàn)槿绻褂脀ebpack會(huì)自動(dòng)安裝webpack4,后面會(huì)產(chǎn)生版本異常*
cnpm install --save webpack@3
#目前版本還是 2.x 不過還是指明出來*
cnpm install --save webpack-dev-server@2
cnpm install --save autoprefixer
cnpm install --save html-webpack-plugin
cnpm install --save extract-text-webpack-plugin
cnpm install --save open-browser-webpack-plugin
cnpm install --save-dev babel-core babel-loader babel-preset-es2015 babel-preset-react babel-preset-stage-0
4.編譯打包
這里不采用,官方提供的build腳本。我們基于webpack創(chuàng)建一個(gè)。
打開**webpack.js 在script中加入下面代碼
"build:example": "webpack --config webpack.config.js --progress --colors -p",
"start:example": "webpack-dev-server --config webpack.config.js --inline --progress --colors --port 8080",
如下:
此時(shí)運(yùn)行腳本:
cnpm run build:example
但是會(huì)發(fā)現(xiàn)報(bào)錯(cuò)了:Mudule not found (js)
這個(gè)沒關(guān)系仔細(xì)看發(fā)現(xiàn)時(shí)缺少了module,用webpack打包會(huì)出現(xiàn)這個(gè)問題。
我們需要全局搜索 ../../../build/packages 并修改成 react-weui
文件很多耐心修改:
舉個(gè)例子:
第5行修改如下:
還有個(gè)錯(cuò)誤:Module not found (css)
打開文件 example/app.js
修改第15行 import 'react-weui/build/packages/react-weui.css';
依次都修改后再運(yùn)行 cnpm run build:example 完美!
5.運(yùn)行example示例項(xiàng)目
cnpm run start:example
完成,打開瀏覽器
6.構(gòu)建并運(yùn)行doc示例項(xiàng)目
因?yàn)閜ackage.json中有了 start:doc腳本,所以我們只需加入
"build:doc": "webpack --config webpack.config.doc.js --progress --colors -p",
下面運(yùn)行
cnpm run build:doc
如果遇到報(bào)錯(cuò)../../build/packages修改為react-weui
這個(gè)構(gòu)建時(shí)間會(huì)稍長(zhǎng)些 耐心等待。。。。 完美!
啟動(dòng)doc
cnpm run start:doc
。。。。頁面一片空白
F12發(fā)現(xiàn)
此處原因是 15.5 以后 prop types分開import,當(dāng)前的react版本已經(jīng)是16.2.0了
// 15.5 以后
import PropTypes from 'prop-types';
找到報(bào)錯(cuò)文件 ***docs/components/preview.js ***修改如下
重新構(gòu)建&運(yùn)行
7.構(gòu)建自己的手腳架
接下來就通過簡(jiǎn)單的模仿,構(gòu)建自己的APP腳手架。
1.創(chuàng)建項(xiàng)目world
2.創(chuàng)建文件 index.html和app.js
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0">
<title>world</title>
</head>
<body ontouchstart>
<div class="container" id="container"></div>
</body>
</html>
app.js
import React, { Component } from "react";
import PropTypes from 'prop-types';
import { render } from "react-dom";
import ReactDOMServer from "react-dom/server";
import { transform } from "babel-standalone";
class Preview extends Component {
static defaultProps = {
previewComponent: "div"
};
static propTypes = {
code: PropTypes.string.isRequired,
scope: PropTypes.object.isRequired,
previewComponent: PropTypes.node,
noRender: PropTypes.bool,
context: PropTypes.object
};
constructor(props){
super(props)
this.state = {
error: null
};
}
_compileCode = () => {
const { code, context, noRender, scope } = this.props;
const generateContextTypes = (c) => {
return `{ ${Object.keys(c).map(val =>
`${val}: React.PropTypes.any.isRequired`).join(", ")} }`;
};
if (noRender) {
return transform(`
((${Object.keys(scope).join(", ")}, mountNode) => {
class Comp extends React.Component {
getChildContext() {
return ${JSON.stringify(context)};
}
render() {
return (
${code}
);
}
}
Comp.childContextTypes = ${generateContextTypes(context)};
return Comp;
});
`, { presets: ["es2015", "react", "stage-1"] }).code;
} else {
return transform(`
((${Object.keys(scope).join(",")}, mountNode) => {
${code}
});
`, { presets: ["es2015", "react", "stage-1"] }).code;
}
};
_setTimeout = (...args) => {
clearTimeout(this.timeoutID); //eslint-disable-line no-undef
this.timeoutID = setTimeout.apply(null, args); //eslint-disable-line no-undef
};
_executeCode = () => {
const mountNode = this.refs.mount;
const { scope, noRender, previewComponent } = this.props;
const tempScope = [];
try {
Object.keys(scope).forEach(s => tempScope.push(scope[s]));
tempScope.push(mountNode);
const compiledCode = this._compileCode();
//console.log(compiledCode);
if (noRender) {
/* eslint-disable no-eval, max-len */
const Comp = React.createElement(
eval(compiledCode).apply(null, tempScope)
);
ReactDOMServer.renderToString(React.createElement(previewComponent, {}, Comp));
render(
React.createElement(previewComponent, {}, Comp),
mountNode
);
} else {
eval(compiledCode).apply(null, tempScope);
}
/* eslint-enable no-eval, max-len */
this.setState({ error: null });
} catch (err) {
this._setTimeout(() => {
this.setState({ error: err.toString() });
}, 500);
}
};
componentDidMount = () => {
this._executeCode();
};
componentDidUpdate = (prevProps) => {
clearTimeout(this.timeoutID); //eslint-disable-line
if (this.props.code !== prevProps.code) {
this._executeCode();
}
};
render() {
const { error } = this.state;
return (
<div>
{error !== null ?
<div className="playgroundError">{error}</div> :
null}
<div ref="mount" className="previewArea"/>
</div>
);
}
}
export default Preview;
3.構(gòu)建build和start腳本
"build:world": "webpack --config webpack.config.world.js --progress --colors -p",
"start:world": "webpack-dev-server --config webpack.config.world.js --inline --progress --colors --port 8080",
4.創(chuàng)建webpack.config.world.js
復(fù)制 webpack.config.js 修改 11,12,13行如下
const jsSourcePath = path.join(__dirname, 'world');
const buildPath = path.join(__dirname, 'build/demo/world');
const sourcePath = path.join(__dirname, 'world');
5.run build&start
cnpm run build:world
cnpm run start:world
最后附上代碼地址:
https://gitee.com/wmdzkey/react-weui-scaffold
看到這里覺得有幫助的同學(xué)給個(gè)贊,點(diǎn)點(diǎn)下面的喜歡,有能力的支持下。多謝~