最近在做一个纯前端的记账项目,技术栈采用React和Typescript,使用VScode编程。这篇文章记录一下创建项目时使用的一些命令行。
创建项目
// 下载CRA
yarn add global create-react-app
// 在当前文件夹创建项目,支持Typescript
create-react-app . --template typescript
项目创建后
- 创建一个
.env文件,输入BROWSER=none,防止每次编译后自动打开浏览器。 .gitignore文件添加/.idea和/.vscode两行。- 提交项目代码
git commit -m "init".
后续遇到的环境配置问题都会记录在这篇文章。
CSS环境配置
在index.css文件添加一句@import-normalize,作用是保证页面在不同浏览器上默认样式相近。
支持SCSS:node-sass网络下载慢,而且需要本地编译,浪费性能,我们采用dart-sass。步骤如下:
- 命令行输入:
yarn add node-sass@npm:dart-sass(切忌直接安装,编译会报错!!!)
import和JS import优化
React不需要@。
在tsconfig.json文件里加入如下代码,JS就不需要@来表示src/目录了。
compilerOptions: {
"baseUrl": "src"
},
"include": [
"src"
]
styled-components: CSS in JS
该项目不写css或scss文件,采用一种"CSS in JS"方案。安装styled-components,命令行输入: yarn add styled-components。
为了更好的使用体验,在vscode插件商店里下载styled-components插件。
react-router应用
安装应用和ts依赖使用如下两行命令
yarn add react-router-dom
yarn add --dev @types/react-router-dom
动态加载文件
需要安装yarn add -D @types/webpack-env。
在需要动态引入svg的tsx文件添加下面的代码
let importAll = (requireContext: __WebpackModuleApi.RequireContext) =>
requireContext.keys().forEach(requireContext);
try {
importAll(require.context('assets/icons', true, /\.svg$/));
} catch (error) {
console.log(error);
}
assets/icos是svg图标存放的位置@types/webpack-env的作用是提供__WebpackModuleApi变量