typescript+react+antd基础环境搭建
typescript+react+antd基础环境搭建(包含样式定制)
- tsconfig.json 配置
// 具体配置可以看上面的链接 这里module moduleResolution的配置都会影响到antd的显示
// allowSyntheticDefaultImports 是antd官网给的配置 必须加上
{
"compilerOptions": {
"outDir": "./dist/",
"sourceMap": false,
"noImplicitAny": false,
"module": "es6",
"target": "es5",
"jsx": "preserve",
"moduleResolution": "node",
"forceConsistentCasingInFileNames": false,
"allowJs": true,
"allowSyntheticDefaultImports": true,
"lib": [
"es5",
"dom",
"dom.iterable",
"es2015"
]
},
"include": [
"./src/**/*"
]
}
- package.json 配置
// 其中很多配置是用来做antd样式定制的
// concurrently 是用来将命令连接起来执行的 Run multiple commands concurrently
{
"name": "power3",
"version": "1.0.0",
"description": "typescript && react for power3",
"main": "index.js",
"scripts": {
"build": "webpack --progress --colors",
"start": "concurrently \"node ./server/server.js\" \" npm run dev \"",
"dev": "webpack-dev-server --progress --colors -p -d"
},
"author": "",
"license": "ISC",
"dependencies": {
"antd": "^2.13.6",
"css-loader": "^0.28.7",
"immutable": "^3.8.2",
"md5": "^2.2.1",
"react": "^15.5.4",
"react-dom": "^15.5.4",
"react-hot-loader": "^3.1.1",
"react-router": "^4.2.0",
"react-router-dom": "^4.2.2"
},
"devDependencies": {
"@types/node": "^8.0.34",
"@types/react": "^16.0.10",
"@types/react-dom": "^16.0.1",
"@types/react-router": "^4.0.15",
"@types/react-router-dom": "^4.0.8",
"awesome-typescript-loader": "^3.2.3",
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-plugin-import": "^1.6.2",
"babel-preset-env": "^1.6.1",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-0": "^6.24.1",
"concurrently": "^3.4.0",
"extract-text-webpack-plugin": "^2.1.0",
"html-webpack-plugin": "^2.30.1",
"less": "^2.7.2",
"less-loader": "^4.0.5",
"less-vars-to-js": "^1.2.0",
"source-map-loader": "^0.2.2",
"style-loader": "^0.19.0",
"typescript": "^2.5.3",
"url-loader": "^0.5.8",
"webpack": "^2.3.3",
"webpack-dev-server": "^2.4.2",
"webpack-hot-middleware": "^2.20.0"
}
}
- routes.tsx页面
该页面主要用来配置路由 指定登录页面
推荐使用react-router-dom 里面的各种接口直接继承感觉很方便
/**
* 路由写到此处 页面一般会有层级关系 此处json对象是按照业务写成层级关系
* 第一种做法是 处理成 平级的路由
* 第二种是 根据业务的层级关系渲染出符合业务的相应导航
* 此处两种都导出 然后在index.tsx中可以两种都试一下
*/
import {RouteProps} from 'react-router-dom'
import Apple from './components/fruits/Apple'
import Banana from './components/fruits/banana'
import Cabbage from './components/vegetables/cabbage'
import Radish from './components/vegetables/radish'
interface PowerRouteProps extends RouteProps{
name:string;
}
export const _routes=[
{
id:'fruits',
name:'水果',
routes:[
{
name:'苹果',
path:'/apple',
component:Apple
},
{
name:'香蕉',
path:'/banana',
component:Banana
}
]
},
{
id:'vegetables',
name:'蔬菜',
routes:[
{
name:'白菜',
path:'/cabbage',
component:Cabbage
},
{
name:'萝卜',
path:'/radish',
component:Radish
}
]
}
];
// 此处变量我之前使用 routes 命名 结果在index.tsx引入时(import {routes} from './routes') 直接报错
// 注意导出变量名和文件名不能一样
export const maproutes = _routes.reduce((ary:PowerRouteProps[],cur:any)=>{
return ary.concat(cur.routes||cur)
},[]).filter(x=>x.path && x.path!=='');
- 简单的业务组件(只为了说明)
其他的组件可以在github上看
// ./components/vegetables/cabbage
import * as React from 'react'
export default class Cabbage extends React.Component{
render(){
return (<p>You need to eat cabbage</p>)
}
}
- 入口文件index.tsx
此处写了两种导航 一种有submenu 一种是使用plain数据直接将所有路由列出
import * as React from 'react'
import * as ReactDOM from 'react-dom'
import {HashRouter, Route, Switch, Link, BrowserRouter} from 'react-router-dom'
// 提供antd的本地语言支持
import {LocaleProvider, Menu} from 'antd'
const MenuItem = Menu.Item;
const SubMenu = Menu.SubMenu;
import {maproutes,_routes} from './routes'
// plain 路由
class Navigation extends React.Component {
render() {
return (
<Menu>
{maproutes.map(route => {
return (
<MenuItem key={route.path}>
<Link to={route.path} key={`route-link-${route.path}`}>{route.name}</Link>
</MenuItem>
)
})}
</Menu>
)
}
}
// 有层级关系的路由
class Navigations extends React.Component {
render() {
return (
<Menu style={{width:200}} mode="inline">
{_routes.map(routes=>{
return (
<SubMenu key={routes.id} title={routes.name}>
{routes.routes.map(route=>{
return (
<MenuItem key={`route-${route.path}`}>
<Link to={route.path} key={`route-link-${route.path}`}>{route.name}</Link>
</MenuItem>
)
})}
</SubMenu>)
})}
</Menu>
)
}
}
class NotFoundView extends React.Component {
render() {
return (
<div className="http-404">
<h2 className="text-info">功能尚未开发完毕</h2>
<h3 className="text-danger">Page not found</h3>
</div>
);
}
}
const Router = () => (
<BrowserRouter>
<Switch>
{maproutes.map(route => {
// return <Route path={route.path} key={`route-path-${route.path}`} location={route.location} component={route.component}/>
return <Route path={route.path} key={`route-${route.path}`} component={route.component}/>
})}
<Route path="/" exact component={Navigations}/>
<Route component={NotFoundView}/>
</Switch>
</BrowserRouter>
)
ReactDOM.render(
<Router/>, document.getElementById('app'));
- 样式定制(使用社区提供的方法)
创建.babelrc文件
在终端(ctrl+`)中输入 type null>.babelrc
.babelrc文件
plugins的配置是为了让antd的样式生效
{
"presets": [
["env"],
"stage-0",
"react"
],
"plugins": [
"react-hot-loader/babel",
["import", { "libraryName": "antd","style": true}]
]
}
- 最后一步 webpack.config.js文件编写
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const path = require('path');
const fs = require('fs');
const lessToJs = require('less-vars-to-js');
// 获取自己定义的要覆盖antd默认样式的文件
const themeVariables = lessToJs(fs.readFileSync(path.join(__dirname, './src/assets/style/themes.less'), 'utf8'));
module.exports = {
entry: "./src/index.tsx",
output: {
filename: "bundle.js",
path: __dirname + "/dist"
},
// Enable sourcemaps for debugging webpack's output.
devtool: "cheap-moudle-source-map",
resolve: {
// Add '.ts' and '.tsx' as resolvable extensions.
extensions: [".ts", ".tsx", ".js", ".json"]
},
devServer: {
port: 8003,
hot: true,
// historyApiFallback: true,
historyApiFallback: {
index: '/react.min.js'
},
contentBase: path.resolve(__dirname, 'dist'),
publicPath: '/'
},
module: {
rules: [
// All files with a '.ts' or '.tsx' extension will be handled by
// 'awesome-typescript-loader'.
{
test: /\.(tsx|ts)?$/,
use: [
{
loader: 'react-hot-loader/webpack'
}, {
loader: 'babel-loader'
}, {
loader: 'awesome-typescript-loader'
}
]
},
// All output '.js' files will have any sourcemaps re-processed by
// 'source-map-loader'.
{
enforce: "pre",
test: /\.js$/,
loader: "babel-loader",
exclude: /node_modules/
}, {
test: /\.less$/,
use: [
{
loader: "style-loader"
}, {
loader: "css-loader"
}, {
loader: "less-loader",
options: {
modifyVars: themeVariables
}
}
]
}, {
test: /\.css$/,
use: ExtractTextPlugin.extract({fallback: 'style-loader', use: 'css-loader', publicPath: '/'})
}, {
test: /\.(png|jpg|jpeg|gif|svg)$/,
loader: 'url-loader?limit=8192&name=[name].[ext]&publicPath='
}
]
},
// When importing a module whose path matches one of the following, just assume
// a corresponding global variable exists and use that instead. This is
// important because it allows us to avoid bundling all of our dependencies,
// which allows browsers to cache those libraries between builds.
externals: {
// "react": "React",
// "react-dom": "ReactDOM"
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html',
title: 'hello ts&react',
inject: false,
minify: {
removeComments: true,
collapseWhitespace: true
},
chunksSortMode: 'dependency'
}),
new ExtractTextPlugin({filename: '[name].css', allChunks: true}),
new webpack.HotModuleReplacementPlugin()
]
};
// 此处是借鉴同事的 啊哈哈哈
const os = require('os');
console.log(`############################################################################`);
console.log(`## os: ${os.type()} ${os.arch()} ${os.release()}`);
console.log(`## ram: ${ (os.freemem() / 1024 / 1024 / 1024) < 1
? (os.freemem() / 1024 / 1024).toFixed(0) + 'MB'
: (os.freemem() / 1024 / 1024 / 1024).toFixed(2) + 'GB'}`);
console.log(`## time: ${new Date()}`);
console.log(`############################################################################`);
来源:https://segmentfault.com/a/1190000011721098
typescript+react+antd基础环境搭建的更多相关文章
- Rails + React +antd + Redux环境搭建
前提条件:node和ruby on rails必须已经安装好(相关安装流程不再此处介绍) 1.nvm.node 2.npm or yarn装一个就好 3.rvm.ruby on rails 4.for ...
- React Native的环境搭建以及开发的IDE
(一)前言 前面的课程我们已经对React Native的环境搭建以及开发的IDE做了相关的讲解,今天我们的主要讲解的是应用设备运行(Running)以及调试方法(Debugging).本节的前提条件 ...
- Spark入门实战系列--2.Spark编译与部署(上)--基础环境搭建
[注] 1.该系列文章以及使用到安装包/测试数据 可以在<倾情大奉送--Spark入门实战系列>获取: 2.Spark编译与部署将以CentOS 64位操作系统为基础,主要是考虑到实际应用 ...
- React Native iOS环境搭建
前段时间React Native for Android发布,感觉React Native会越来越多的公司开始研究.使用.所以周六也抽空搭建了iOS的开发环境,以便以后利用空闲的时间能够学习一下. 废 ...
- EXT 基础环境搭建
EXT 基础环境搭建使用 Sencha CMD 下载地址 https://www.sencha.com/products/extjs/cmd-download/ Sencha CMD 常用命令 API ...
- IOS开发基础环境搭建
一.目的 本文的目的是windows下IOS开发基础环境搭建做了对应的介绍,大家可根据文档步骤进行mac环境部署: 二.安装虚拟机 下载虚拟机安装文件绿色版,点击如下文件安装 获取安装包: ...
- Spark环境搭建(上)——基础环境搭建
Spark摘说 Spark的环境搭建涉及三个部分,一是linux系统基础环境搭建,二是Hadoop集群安装,三是Spark集群安装.在这里,主要介绍Spark在Centos系统上的准备工作--linu ...
- 【1】windows下IOS开发基础环境搭建
一.目的 本文的目的是windows下IOS开发基础环境搭建做了对应的介绍,大家可根据文档步骤进行mac环境部署: 二.安装虚拟机 下载虚拟机安装文件绿色版,点击如下文件安装 获取安装包: ...
- react+webpack+babel环境搭建
[react+webpack+babel环境搭建] 1.react官方文档推荐使用 babel-preset-react.babel-preset-es2015 两个perset. Babel官方文档 ...
随机推荐
- 对话框处理Enter,Esc键相应问题
在类视图里面选择你要实现的类,右键属性,在属性里面找到函数PreTranslateMessage,然后添加PreranslateMessage的消息函数,在PreTranslateMessage的消息 ...
- LOJ#3119 随机立方体
解:极大值至少为1.我们尝试把最大那个数的影响去掉. 最大那个数所在的一层(指一个三维十字架)都是不可能成为最大值的. 考虑容斥.我们试图求除了最大值以外至少有k个极大值的概率. 我们钦定某k个位置是 ...
- Ionic跳转到外网地址
1.安装插件 https://github.com/apache/cordova-plugin-inappbrowser 执行命令:cordova plugin add org.apache.cord ...
- 19-10-24-J-快乐?
向未来的大家发送祝福(不接受的请自动忽略): 祝大家程序员节快乐! 好了. ZJ一下 额. 考场上差点死了. 码1h后,T1还没过大样例. 我×××. 后来发现是自己××了. T2T3丢暴力. 比咕的 ...
- 深入浅出 Java Concurrency (23): 并发容器 part 8 可阻塞的BlockingQueue (3)[转]
在Set中有一个排序的集合SortedSet,用来保存按照自然顺序排列的对象.Queue中同样引入了一个支持排序的FIFO模型. 并发队列与Queue简介 中介绍了,PriorityQueue和Pri ...
- 第一个SpringBoot插件-捕获请求并且支持重新发起
SpringBoot 插件入门 简介 公司用的是SpringBoot,api框架用的是swagger-ui,确实用的不错,但是在使用过程中发现一个问题,就是当前端正式调用的时候,如果参数一多的话模拟请 ...
- python中的*args与**kwargs的含义与作用
在定义函数的时候参数通常会使用 *args与**kwgs,形参与实参的区别不再赘述,我们来解释一下这两个的作用. *args是非关键字参数,用于元组,**kwargs是关键字参数 (字典)例如下面的代 ...
- nodejs+express 初学(一)
以下都是windows环境 1.下载nodejs http://www.nodejs.org/download/ 然后安装 2.确认已经安装完成 . node -v 3.安装express 注意: 是 ...
- org.apache.ant实现压缩和解压
<dependency> <groupId>org.apache.ant</groupId> <artifactId>ant</artifactI ...
- JDK8日期时间操作小汇总
统一使用java.time.*包下的类 1.获取当前的日期.时间.日期加时间 LocalDate todayDate = LocalDate.now(); //今天的日期 LocalTime now ...