平时进行开发大多数是基于vue-cli或者create-react-app等官方或者公司内部搭建的脚手架。css
咱们业务仔作的最多就是npm i和npm run dev或者npm start,而后在router文件夹上添加路由,在views或者pages文件夹中添加业务页面。这种快速开发对公司固然是好事,但对于开发人员来讲对项目里的webpack封装和配置了解的不清楚,出问题时很容易会不知如何解决,或者不会经过webpack去扩展新功能和优化编译速度。出去是没多大竞争力的,并且很容易被替代。html
接下来一步一步的演示如何搭建基于TypeScript与React的一个开发环境。vue
项目代码:github.com/zhangwinwin…
(会不定时更新)node
webpack是一个开源的JavaScript模块打包工具,其核心是解决模块之间的依赖,把各个模块按照特定的规则和顺序组织在一块儿,最终合并为一个JS文件(有时会有多个)。这个过程就叫做模块打包。react
Webpack就比如一个模块处理工厂,咱们把源代码交给Webpack,由它进行加工、拼装处理,产出最终的资源文件,等待送往客户。webpack
运行npm init会生成一个package.json文件,里面包含一些项目的基本信息git
npm init
复制代码
webpack4将命令行相关的单独拆了出去封装成了webpack-cli。因此得安装webpack与webpack-cligithub
npm install webpack webpack-cli -D
复制代码
ps:在开始以前,请确保安装了Node.js的最新版本。web
webpack4号称零配置。它提供mode配置选项(详情请看文档),告知webpack使用相应模式的内置优化。vue-cli
用法以下:
// 在webpack配置文件中使用
module.exports = {
mode: 'production'
};
// 在命令行中使用
webpack --mode=production
复制代码
console.log('hello, world')
复制代码
"scripts": {
"dev": "webpack ./src/main.js --mode development"
},
复制代码
运行 npm run dev。若是出现dist/main.js说明运行成功。
"scripts": {
"dev": "webpack --config webpack.config.js --mode development"
},
复制代码
安装依赖
npm install babel-loader @babel/core @babel/cli @babel/preset-env -D
npm install core-js regenerator-runtime -S
复制代码
简单说明一下:
@babel/preset-env提供了一个useBuiltIns参数,设置值为usage时,就只会包含代码须要的polyfill。有一点须要注意:配置此参数的值为usage,必需要同时设置corejs。
建立babel.config.js
module.exports = {
presets: [
[
'@babel/env',
{
useBuiltIns: 'usage',
corejs: 3
}
]
]
};
复制代码
修改webpack配置
module.exports = {
entry: ...,
output: ...,
+ module: {
+ rule: [
+ {
+ test: /\.(js|ts)x?$/, //jsx或者tsx文件
+ exclude: /(node_modules)/, // 排除node_modules
+ use: {
+ loader: 'babel-loader'
+ }
+ }
+ ]
}
}
复制代码
npm install sass-loader dart-sass css-loader style-loader file-loader -D
复制代码
module.exports = {
entry: ...,
output: ...,
module: {
rule: [
...,
+ {
+ test: /\.(c|sc|sa)ss$/,
+ use: [
+ 'style-loader',
+ 'css-loader',
+ {
+ loader: 'sass-loader',
+ options: {
+ implementation: require('dart-sass')
+ }
+ }
+ ]
+ },
+ {
+ test: /\.(png|jpg|gif|woff|svg|ttf)$/,
+ use: [
+ 'file-loader'
+ ]
+ }
]
}
}
复制代码
HtmlWebpackPlugin简化了HTML文件的建立,以便为你的webpack包提供服务。这对于在文件名中包含每次会随着编译而发生变化哈希的webpack bundle尤为有用。
npm i html-webpack-plugin -D
复制代码
+ const HtmlWebpackPlugin = require('html-webpack-plugin');
...
module.exports = {
entry: ...,
output: {...},
module: {...},
+ plugins: [
+ new HtmlWebpackPlugin({
+ template: path.join(__dirname, 'public/index.html'),
+ title: 'ts-react-starter',
+ filename: 'index.html'
+ }),
+ ]
}
复制代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title><%= htmlWebpackPlugin.options.title %></title>
</head>
<body>
<div id="root"></div>
</body>
</html>
复制代码
webpack-dev-server可以用于快速开发应用程序,能够实现不刷新页面的状况下,更新咱们的页面。
npm i webpack-dev-server -D
复制代码
module.exports = {
entry: ...,
output: {...},
module: {...},
plugins: [...],
+ devServer: {
+ contentBase: path.resolve(__dirname, buildPath),
+ compress: true,
+ port: 9000
}
}
复制代码
"scripts": {
"dev": "webpack-dev-server --open"
},
复制代码
npm i react react-dom react-router-dom -S
npm i @babel/preset-react -D
复制代码
module.exports = {
presets: [
...,
+ '@babel/preset-react'
]
};
复制代码
import React from 'react';
import ReactDOM from 'react-dom';
import {
BrowserRouter as Router,
Route
} from "react-router-dom";
import 'core-js/stable';
import 'regenerator-runtime/runtime';
const Root = document.getElementById('root');
const Test = () => <div className="test">test</div>;
ReactDOM.render(
<Router>
<Route path='/' component={Test}>
</Route>
</Router>,
Root
);
复制代码
修改webpack.config.js中的entry为src/index.jsx。
运行npm run dev便可看到效果。
社区已经记录了90%的顶级JavaScript库。这意味着,你能够很是高效地使用这些库,而无需在单独的窗口打开相应文档。能够经过npm来安装使用@types
npm i @types/react @types/react-dom @types/react-router-dom typescript @babel/preset-typescript -D
复制代码
module.exports = {
presets: [
...,
+ '@babel/preset-typescript'
]
};
复制代码
{
"compilerOptions": {
"target": "ES2016",
"module": "commonjs",
"jsx": "react",
"strict": true,
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"inlineSourceMap": true
},
"include": [
"src"
]
}
复制代码
将css独立拆包最大的好处就是js和css的改动,不会影响对方。好比我改了js文件并不会致使css文件的缓存失效。
使用方式也很简单,你们看着文档抄就能够了。
npm i mini-css-extract-plugin -D
复制代码
修改webpack.config.js
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
module: {
rules: [
...
{
test: /\.(c|sc|sa)ss$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
hmr: process.env.NODE_ENV === 'development'
}
},
...
]
},
]
},
plugins: [
...
new MiniCssExtractPlugin({
filename: 'index.css'
}),
],
}
复制代码
打包css以后还须要作css代码压缩,这时候须要使用optimize-css-assets-webpack-plugin这个插件,它不只能压缩css还能优化代码。
npm i cssnano optimize-css-assets-webpack-plugin -D
复制代码
修改webpack.config.js
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
module.exports = {
plugins: [
...
new OptimizeCSSAssetsPlugin({
assetNameRegExp: /index\.css$/g,
cssProcessor: require('cssnano'),
cssProcessorPluginOptions: {
preset: ['default', { discardComments: { removeAll: true } }]
},
canPrint: true
})
],
}
复制代码
优化webpack就介绍到这里,掘金已有不少很是好的优化文章,请自行搜索并实践。
到目前为止,已经成功的本身搭建了一个typescript+react的开发环境。在搭建过程当中,仍是会踩不少坑的。
世上无难事,只怕有心人。动手试一试,比看半天都要好。
更多文章请移步楼主github,若是喜欢请点一下star,对做者也是一种鼓励。