React +typescript development mode, plus ANTD development experience is quite good. This article focuses on the problems encountered in building scaffolding on the basis of the official recommended scaffolding.
I started withcreate-react-app-typescriptScaffolding (this scheme has been abandoned)
npx create-react-app my-app --scripts-version=react-scripts-ts
cd my-app
npm start
# or with yarn
yarn create react-app my-app --scripts-version=react-scripts-ts
cd my-app
yarn start
Copy the code
However, this scaffold, which the author has stopped updating, has been archived on github repository:
This repository has been archived by the owner. It is now read-only.
Copy the code
Because the earlier version of the dependency package Webpack-dev-server has vulnerabilities, it is best to upgrade to a version greater than 3.1.11
CVE-2018-14732
Vulnerable versions: < 3.1.11
Patched version: 3.1.11
An issue was discovered in lib/Server.js inWebpack-dev-server before 3.1.11. Now They are able to Steal Developer's code because the origin of requests is not checked by the WebSocket server, which is used for HMR (Hot Module Replacement). Anyone can receive the HMR message sent by the WebSocket server via a Ws ://127.0.0.1:8080/ connection from any origin.Copy the code
However, upgrading Webpack-dev-server involves a series of toolchain package upgrades, which can be cumbersome to upgrade on the existing scaffolding and subsequent configuration changes. The following method is then used
New scaffolding: Create React App Adding TypeScript
1, referenceThis article addressesMethod in
// Run the yarn eject command to separate configurations for later modificationCopy the code
2. Since tsLint does not exist in the default scaffolding, to use tsLint, you need to add tslint.json to the root directory, install the package, and modify the configuration
yarn add tslint tslint-config-prettier tslint-react
Copy the code
- Tslint. json configuration (reference) is as follows:
{
"extends": ["tslint:recommended"."tslint-react"."tslint-config-prettier"]."rules": {"no-console":false."no-debugger":false."indent": [true."spaces", 2], // Indent"no-consecutive-blank-lines": [// no more than two blank linestrue, 2),"jsx-no-lambda": false// Check the order of keys in the object"object-literal-sort-keys": false// Import the collation of the source"ordered-imports": true
},
"linterOptions": {
"exclude": [
"config/**/*.js"."node_modules/**/*.ts"]}}Copy the code
- Add to paths.js file
appTsLint: resolveApp("tslint.json")
As follows:
module.exports = {
dotenv: resolveApp(".env"),
appPath: resolveApp("."),
appBuild: resolveApp("build"),
appPublic: resolveApp("public"),
appHtml: resolveApp("public/index.html"),
appIndexJs: resolveModule(resolveApp, "src/index"),
appPackageJson: resolveApp("package.json"),
appSrc: resolveApp("src"),
appTsConfig: resolveApp("tsconfig.json"),
+ appTsLint: resolveApp("tslint.json"),
yarnLockFile: resolveApp("yarn.lock"),
testsSetup: resolveModule(resolveApp, "src/setupTests"),
proxySetup: resolveApp("src/setupProxy.js"),
appNodeModules: resolveApp("node_modules"),
publicUrl: getPublicUrl(resolveApp("package.json")),
servedPath: getServedPath(resolveApp("package.json"))
};
Copy the code
- Webpack. Config. Js modified plug-in ForkTsCheckerWebpackPlugin configuration, increase
tslint: paths.appTsLint
That is as follows:
new ForkTsCheckerWebpackPlugin({ typescript: resolve.sync("typescript", { basedir: paths.appNodeModules }), async: false, checkSyntacticErrors: true, tsconfig: paths.appTsConfig, + tslint: paths.appTsLint, compilerOptions: { module: "esnext", moduleResolution: "node", resolveJsonModule: true, isolatedModules: true, noEmit: true, jsx: "preserve" }, reportFiles: [ "**", "!**/*.json", "!**/__tests__/**", "!**/?(*.)(spec|test).*", "!**/src/setupProxy.*", "! **/src/setupTests.*" ], watch: paths.appSrc, silent: true, formatter: typescriptFormatter })Copy the code
The use of tslint with vscode can be found here
Using path aliases
Typescript project path aliases are not configured in Webpack, but in tsconfig.json.
For example, add the following configuration to tsconfig.json:
{ "compilerOptions": { + "baseUrl": ".", + "paths": { + "@/*": ["src/*"] + }, ... },... }Copy the code
Used in index.tsx:
import App from "@/App";
Copy the code
Start the project at this point
yarn start
Copy the code
The following compilation error occurs:
Failed to compile.
./src/index.tsx
Module not found: Can't resolve '@/App' in 'dir/dir/src'
Copy the code
Resolve compilation errors
yarn add tsconfig-paths-webpack-plugin
Copy the code
Modify the webpack.config.js file
+ const TsconfigPathsPlugin = require("tsconfig-paths-webpack-plugin");. alias: { // Support React Native Web // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/ "react-native": "react-native-web" }, plugins: [ // Adds support for installing with Plug'n'Play, leading to faster installs and adding // guards against forgotten dependencies and such. PnpWebpackPlugin, // Prevents users from importing files from outside of src/ (or node_modules/). // This often causes confusion because we only process files within src/ with babel. // To fix this, we prevent you from importing files out of src/ -- if you'd like to, // please link the files into your node_modules/ and let module-resolution kick in. // Make sure your source files are compiled, as they will not be processed in any way. new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]), + new TsconfigPathsPlugin() ]Copy the code
Using antd
Although ANTD has some mature scaffolds, I feel that they are too redundant, or it will be troublesome to modify them later, so I prefer to combine official scaffolds to make a familiar one.
yarn add antd
Copy the code
Use the antD tutorial to get started and quickly introduce ANTD to our React +typescript projects.
And of course for performance,According to the need to load
We still have to do it. Install itbabel-plugin-importAnd add related configurations
yarn add babel-plugin-import
Copy the code
Modify the webpack.config.js file
{
test: /\.(js|mjs|jsx|ts|tsx)$/,
include: paths.appSrc,
loader: require.resolve("babel-loader"),
options: {
customize: require.resolve(
"babel-preset-react-app/webpack-overrides"
),
plugins: [
[
require.resolve("babel-plugin-named-asset-import"),
{
loaderMap: {
svg: {
ReactComponent: "@svgr/webpack?-svgo![path]"
}
}
}
],
+ [
+ "import",
+ {
+ libraryName: "antd",
+ style: "css"
+ }
+ ]
],
// This is a feature of `babel-loader` for webpack (not Babel itself).
// It enables caching results in ./node_modules/.cache/babel-loader/
// directory for faster rebuilds.
cacheDirectory: true,
cacheCompression: isEnvProduction,
compact: isEnvProduction
}
},
Copy the code
The scaffolding is now complete!
The react – app – antd – ts scaffold