最近導師安排了一個任務,將一個已配置好的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