项目说明
基于react-scripts的小改造。
- 将默认端口号改为3001
- 支持less
- 支持scss
- 支持装饰器(注解)
- 在index.js中默认引入antd-css-rewrite模块。webpack配置中集成antd css动态加载
- prod环境生成持久缓存的verdor.min.js
- prod环境去掉sourceMap
- 支持react组件热更新
- 正式环境移除propTypes
- 在
yarn build
时,拷贝public目录里面的内容时会过滤data
文件夹,通常这个里面是放mock数据的。 - 添加
babel-runtime
按需加载,解决不支持es6 7的语法糖,然而如果要解决API层面的,建议自己去引入“core-js”里面的模块。 - 默认生成apps.config.js文件,用来配置多入口、alias配置、eslint配置以及webpack分析器的开关,譬如:
module.exports = {
entryList: [
{
name: "index",
path: "index.js",
templatePath: "index.html"
},
{
name: "login",
path: "login.js",
templatePath: "login.html"
},
...
],
alias: {
"Component": path.resolve(__dirname, 'src/component/')
},
eslintRule: {
"globals": {
"$": true
}
},
analyzerWebpack: {
turn: "off",
port: 11111
},
theme: {
}
}
- 默认生成.env文件,提供三个配置:PORT(项目启动端口号)、myProxy(转发请求的URL)、TITLE(项目title,会改写index.html中的title),即可以在.env里面这样写:
PORT=3003
myProxy=http://localhost:6002
TITLE=代账宝
{
"dependencies": {
"antd": "^2.7.4",
"axios": "^0.16.1",
"prop-types": "^15.5.10",
"antd-css-rewrite": "^1.0.0",
"babel-runtime": "^6.25.0",
"react-router": "^3.0.2"
}
}
默认react及react-dom是有的
publicPath说明
主要用来解决最终项目的URL:http://xxx.com/xxx
,xxx这个目录下,而非http://xxx.com
。
像之前代账宝使用中,webpack.config.prod.js中,有这样的一段配置
{
publicPath: "/dzb"
}
我在这个配置中,未改,那么怎么实现上面的功能呢?很容易(读源码还是需要费点时间的),在package.json中新增homepage
字段:
{
"homepage": "dzb"
}
这样写即可。
常量(DefinePlugin)说明
在js中可以通过process.env
来取以下变量:
- NODE_ENV
- PUBLIC_URL
- TITLE
- URL_PREFIX
简单说一下URL_PREFIX
。这个需求是这样的:
nginx不配转发,直接URL请求过去。当然这个服务器得配置允许跨域才行。
由于开发环境和build环境的URL_PREFIX是不一样的。所以需要写到package.json中,写法如下:
{
"build": "cross-env URL_PREFIX=http://www.a.com mior-react-scripts build"
}
多个环境就配置多个。。(cross-env,需要自己安装一下,yarn add cross-env -D
)
动态import说明
譬如:
async componentDidMount() {
const {default: Util} = await import("./Util");
console.dir(Util);
}
sass说明
如果用的是npm,则可以直接跳过这个。
用的是yarn,在命令中运行一下以下两条命令:
yarn config set registry https://registry.npm.taobao.org -g
yarn config set sass_binary_site http://cdn.npm.taobao.org/dist/node-sass -g #sass二进制包
备注:有时候淘宝源并不是很稳定,可以全局装一下“yrm”,它可以管理yarn和npm的镜像资源,当淘宝源不行时,切换成其他的即可。
apps.config.js中的theme字段说明
可以用它来改写antd中的less变量,比如:
{
"@body-background": "#000",
"@icon-url": "'字体地址'"
}
这里需要注意的是字体地址那里要加一个单引号,可以是线上字体库,也可以是本地字体库,具体可以参考local-iconfont,它会将这个地址去拼.svg
等后缀。
本地字体库,在build时,如果有homepage
,它生成的会有问题,即不会加上前缀。
这里我就不考虑处理了,我的建议是用阿里巴巴的Icon库生成在线字体库
,而不是下载下来,好几个文件放在font目录下,没有这个必要。
使用
create-react-app 要创建的目录名称 --scripts-version mior-react-scripts
react替代方案
preact
'react': 'preact-compat',
'react-dom': 'preact-compat',
// Not necessary unless you consume a module using `createClass`
'create-react-class': 'preact-compat/lib/create-react-class'
将这一段拷贝到apps.config.js
的alias中,然后yarn add preact-compat -S
即可。
react-lite
'react': 'react-lite',
'react-dom': 'react-lite'
将这一段拷贝到apps.config.js
的alias中,然后yarn add react-lite -S
即可。
测试了一下,体积大概能减少至一半。
inferno
'react': 'inferno-compat',
'react-dom': 'inferno-compat'
将这一段拷贝到apps.config.js
的alias中,然后yarn add inferno inferno-compat -S
即可。
后续工作