前提条件:已经安装node.js,可以使用npm,cnpm
为了避免自己忘了,所以记录一下
然后新建项目文件夹,控制台执行:npm init -y
1.安装react相关依赖
cnpm install --save-dev react react-dom @types/react @types/react-dom
2.安装typescript依赖,并初始化tsconfig,除了tsc init,也可以直接在根目录下新建tsconfig.json
cnpm install --save-dev typescript
tsc init
项目的tsconfig.json参考
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
"experimentalDecorators": true
},
"include": [
"src"
]
}
3.安装代码质量检测包 eslint,babel-eslint,
cnpm install --save-dev eslint babel-eslint
npx eslint --init
4.安装webpack
cnpm install --save-dev webpack webpack-cli html-webpack-plugin
5.安装babel相关的依赖
cnpm install babel-loader @babel/plugin-transform-runtime @babel/preset-env @babel/preset-react
cnpm install --save-dev @babel/preset-typescript @babel/plugin-syntax-jsx
6.配置webpack配置文件,如webpack.config.js
const path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const { resolve } = require('path');
const { DefinePlugin } = require('webpack');
const ENV = process.env.ENV;
const isProd = ENV === 'production';
module.exports = {
mode: 'development', //打包为开发模式
// 入口配置的对象中,属性为输出的js文件名,属性值为入口文件
entry: './src/index.tsx', //入口文件,从项目根目录指定
output: { //输出路径和文件名,使用path模块resolve方法将输出路径解析为绝对路径
path: path.resolve(__dirname, './dist'), //将js文件打包到dist/js的目录
filename: isProd ? '[name]/[hash].js' : '[name]/index.js'
// filename: '[name]@[chunkhash].js'
// filename: "js/[name]-[hash].js" //使用[name]打包出来的js文件会分别按照入口文件配置的属性来命名
},
devtool: 'source-map',
resolve: { extensions: [".ts", ".tsx", ".js", ".jsx", ".json"] },
module: {
rules: [
{
test: /\.(js|mjs|jsx|ts|tsx)$/,//一个匹配loaders所处理的文件的拓展名的正则表达式,这里用来匹配js和jsx文件(必须)
exclude: /node_modules/,//屏蔽不需要处理的文件(文件夹)(可选)
loader: 'babel-loader',//loader的名称(必须)
options: {
presets: ['@babel/preset-typescript', '@babel/preset-react', '@babel/preset-env'],
plugins: ["@babel/plugin-syntax-jsx", "@babel/plugin-transform-runtime"],
cacheDirectory: true,
},
},
],
},
plugins: [
new HtmlWebpackPlugin(
{
template: './public/index.html',
filename: resolve('./dist/index.html'),
}
),
],
devServer: {
open: true,
historyApiFallback: true, // 不跳转
hot: true, // 开启热更新
// liveReload: true,
port: 8008,
}
};
也有博客使用awesome-typescript-loader
{
test: /\.tsx?$/,
loader: "awesome-typescript-loader"
}
6.在package.json里的"scripe"里配置启动命令
"start": "webpack serve --config webpack.config.js"
7,启动项目
npm start
代码地址:https://github.com/letterletter/lerna-demo/tree/master/packages/react_ts_webpack