最近导师安排了一个任务,将一个已配置好的React、Webpack4等具备市场上常见功能的模板添加上TypeScript。俗话说:环境配置三小时,Coding不足5分钟。配置环境真的很是浪费时间,所以写个文章记录下,但愿能对各位要配置TS的前端们有所帮助。 javascript
先放上完整配置好的项目地址: github.com/dcison/Reac…css
├── .babelrc
├── .eslintrc
├── .gitignore
├── index.html
├── package.json
├── tsconfig.json
├── src
│ ├── reducers
│ ├── components
│ ├── actions.ts
│ ├── global.styl
│ ├── index.tsx
│ └── store.ts
└── static
复制代码
// src/index.js
import type from './components/Apple'
console.log(type)
// src/components/Apple.js
export default {
type: 'apple'
}
复制代码
import path from 'path';
export default {
mode: 'development',
devtool: 'eval',
entry: {
index: './src/index.js',
},
output: {
publicPath: '/',
filename: 'js/[name].js',
chunkFilename: 'js/[name].js',
path: path.resolve(__dirname, 'dist')
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
}
]
},
devServer: {
port: 3000
},
resolve: {
extensions: [
'.jsx',
'.js',
'.ts',
'.tsx'
]
}
};
复制代码
{
"presets": [
"@babel/preset-env"
],
"plugins": [
]
}
复制代码
{
"scripts": {
"start": "webpack-dev-server --content-base"
},
"devDependencies": {
"@babel/cli": "^7.2.3",
"@babel/core": "^7.2.2",
"@babel/preset-env": "^7.3.1",
"@babel/register": "^7.0.0",
"babel-loader": "^8.0.5",
"webpack": "^4.29.0",
"webpack-cli": "^3.2.1",
"webpack-dev-server": "^3.1.14"
},
}
复制代码
entry: {
index: './src/index.tsx',
},
{
test: /\.tsx?$/,
exclude: /node_modules/,
use: {
loader: 'ts-loader'
}
}
复制代码
{
"compilerOptions": {
"module": "esnext",
"target": "es5",
"lib": ["es6", "dom"],
"sourceMap": true,
"jsx": "react",
"noImplicitAny": true,
"allowJs": true,
"moduleResolution": "node"
},
"include": [
"src/*"
],
"exclude": [
"node_modules"
]
}
复制代码
{
"env": {
"browser": true,
"es6": true
},
"extends": "eslint:recommended",
"parserOptions": {
"ecmaFeatures": {
"experimentalObjectRestSpread": true,
"jsx": true
},
"sourceType": "module"
},
"parser": "typescript-eslint-parser",
"plugins": [
"react",
"typescript"
],
"rules": {
//... 自行添加规则
}
}
复制代码
"eslint.validate": [
"javascript",
"javascriptreact",
{
"language": "typescript",
"autoFix": true
},
{
"language": "typescriptreact",
"autoFix": true
}
]
复制代码
import HtmlWebpackPlugin from 'html-webpack-plugin';
plugins: [
new HtmlWebpackPlugin({
title: '模板',
hash: false,
filename: 'index.html',
template: './index.html',
})
]
复制代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title><%= htmlWebpackPlugin.options.title || ''%></title>
</head>
<body>
<div id="root"></div>
</body>
</html>
复制代码
"presets": [
"@babel/preset-env",
"@babel/preset-react" // 添加这条
],
复制代码
import * as React from 'react';
import * as ReactDOM from "react-dom";
class SomeComponent extends React.Component<{}, {}> {
render () {
return <div>hello</div>;
}
}
ReactDOM.render(
<SomeComponent/>,
document.getElementById('root')
);
复制代码
{
test: /\.css$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
localIdentName: '[path][name]__[local]--[hash:base64:5]'
}
}
]
}
复制代码
import './global.css';
复制代码
{
test: /\.styl$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
modules: true,
import: true,
importLoaders: 1,
localIdentName: '[path][name]__[local]--[hash:base64:5]'
}
},
{ loader: 'stylus-loader' },
]
},
复制代码
2.15日 追加: 添加typings-for-css-modules-loaderhtml
yarn add -D typings-for-css-modules-loader css-loader@^1.0.1
(css-loader 2.x版本以上有问题){
test: /\.styl$/,
use: [
'style-loader',
{
loader: 'typings-for-css-modules-loader',
options: {
modules: true,
namedExport: true,
camelCase: true,
minimize: true,
localIdentName: "[local]_[hash:base64:5]",
stylus: true
}
},
{ loader: 'stylus-loader' },
]
},
复制代码
import * as styles from './apple.styl';
<div className={styles.redFont}>测试文字</div>
复制代码
坑前端
这里咱们遇到一个坑,全部的css-moduels/typings-for-css-modules-loader教程并不会告诉你这里include配置不写会形成什么影响。当咱们此前没有写这句话的时候,d.ts由于索引速度不够快,或者说没有在内部自动创建联系(这里缘由比较迷),会致使咱们命令行和窗口直接报未找到类型的错误,须要手动从新编译一次,效率极低,当咱们加上include后就能够随便折腾了(迷)include:path.resolve('src/')java
不知为什么,添加inclue配置后,依旧会报未找到对应的样式模块错(但此时对应的.d.ts声明文件已经生成)。因为开启了热更新,不须要再次从新编译,改动一个小内容触发一下webpack的热更新便可正常使用。node
第二个坑,若是你只引用,而不用,会没法生成对应的.d.ts文件,所以会打包失败react
devServer: {
historyApiFallback: true
}
复制代码
// src/components/Apple.tsx
import * as React from 'react';
class Apple extends React.Component<any, any> {
state = {
text: 'iphone XR'
}
handleChange = () => {
this.setState({
text: 'iphone8'
});
}
render () {
return <>
<button onClick={this.handleChange}>点我换机子</button>
{this.state.text}
</>;
}
}
export default Apple;
// src/components/xiaomi.tsx
// 代码结构相似,就只改了下text的内容,因此不放了
// text: 'xiaomi 8'
复制代码
import * as React from 'react';
import * as ReactDOM from "react-dom";
import { BrowserRouter, Route, Redirect, Switch, Link } from 'react-router-dom';
import Apple from './components/Apple';
import Xiaomi from './components/XiaoMi';
import './global.styl';
const Header = () => (
<ul>
<li><Link to="/">苹果</Link></li>
<li><Link to="/phone/xiaomi">小米</Link></li>
</ul>
);
ReactDOM.render(
<div>
<BrowserRouter>
<>
<Header />
<Switch>
<Route path="/phone/apple" component={Apple} />
<Route path="/phone/xiaomi" component={Xiaomi} />
<Redirect to="/phone/apple" />
</Switch>
</>
</BrowserRouter>
</div>,
document.getElementById('root')
);
复制代码
import * as React from "react";
export default function asyncComponent (importComponent: any) {
class asyncComponent extends React.Component<any, any> {
constructor (props: any) {
super(props);
this.state = {
component: null
};
}
async componentDidMount () {
const { default: component } = await importComponent();
this.setState({
component: component
});
}
render () {
const C = this.state.component;
return C ? <C {...this.props} /> : null;
}
}
return asyncComponent;
}
复制代码
import asyncComponent from "./components/asyncComponent";
const Apple = asyncComponent(() => import("./components/Apple"));
const XiaoMi = asyncComponent(() => import("./components/XiaoMi"));
复制代码
import webpack from 'webpack';
plugins: [
new webpack.HotModuleReplacementPlugin()
],
devServer: {
hot: true
},
复制代码
if (module.hot) {
module.hot.accept();
}
复制代码
export const initPhone = (data: object) => {
return {
type: 'INIT_PHONE',
data
};
};
export const setPhoneMoney = (data: object) => {
return {
type: 'SET_MONEY',
data
};
};
复制代码
// src/reducers/Phone.ts
var initState = {
name: '',
money: 0
};
export default function (state = initState, action: any) {
switch (action.type) {
case 'INIT_PHONE':
return {
...state,
name: action.data.name,
money: action.data.money
};
case 'SET_MONEY':
return {
...state,
money: action.data.money
};
default:
return state;
}
}
复制代码
import { createStore, applyMiddleware, combineReducers } from 'redux';
import thunkMiddleware from 'redux-thunk';
import Phone from './reducers/Phone';
const rootReducer = combineReducers({
Phone
});
const createStoreWithMiddleware = applyMiddleware(
thunkMiddleware,
)(createStore);
function configureStore (initialState?: any) {
return createStoreWithMiddleware(rootReducer, initialState);
}
export default configureStore();
复制代码
import * as React from 'react';
import { connect } from 'react-redux';
import * as action from '../actions';
class Apple extends React.Component<any, any> {
componentDidMount () {
this.props.initPhone({ name: '苹果8', money: 10000 });
}
handleChange = () => {
this.props.setPhoneMoney({ money: this.props.money - 20 });
}
render () {
return <>
<button onClick={this.handleChange}>点我降价</button>
{this.props.name} 如今仅售价 {this.props.money}
</>;
}
}
function mapStateToProps (state: any) {
return {
name: state.Phone.name,
money: state.Phone.money
};
}
export default connect(mapStateToProps, action)(Apple);
复制代码
import { Provider } from 'react-redux';
import store from './store';
<Provider store={store}> //用该容器包裹一下
<BrowserRouter>
<>
<Header />
<Switch>
<Route path="/phone/apple" component={Apple} />
<Route path="/phone/xiaomi" component={XiaoMi} />
<Redirect to="/phone/apple" />
</Switch>
</>
</BrowserRouter>
</Provider>
复制代码
"scripts": {
"precommit": "lint-staged"
},
"lint-staged": {
"*.{ts,tsx}": [
"eslint --fix",
"git add"
]
}
复制代码
因为该文是边配置编写的,时间跨度也有点大,致使写文的思路断断续续,也未作过多的文字润色,给看到最后的读者们递眼药水。webpack