为了让项目的配置灵活性更高,不使用 create-reate-app 一键搭建项目,而是手动搭建 React 对应的配置项。

安装

安装 React 相关:

  1. npm install --save-dev react react-dom @types/react @types/react-dom

安装TypeScript相关

  1. npm install --save-dev typescript esbuild-loader

为提高性能,摒弃了传统的 ts-loader,选择最新的 esbuild-loader。

配置

修改通用环境配置文件 webpack.commom.js:

  1. const paths = require('./paths');
  2. module.exports = {
  3. // 导入文件可以省略后缀
  4. resolve: {
  5. extensions: ['.tsx', '.ts', '.js'],
  6. },
  7. module: {
  8. rules: [
  9. // 配置typescript的解析器
  10. {
  11. test: /\.(js|ts|jsx|tsx)$/,
  12. include: paths.appSrc,
  13. use: [
  14. {
  15. loader: 'esbuild-loader',
  16. options: {
  17. loader: 'tsx',
  18. target: 'es2015',
  19. },
  20. }
  21. ]
  22. },
  23. ]
  24. }
  25. }

项目配置兼容TypeScript

TypeScript 是 JavaScript 的超集,为其增加了类型系统,可以编译为普通 JavaScript 代码。

为兼容 TypeScript 文件,新增 typescript 配置文件 tsconfig.json:

tsconfig.json

  1. {
  2. "compilerOptions": {
  3. "outDir": "./dist/",
  4. "noImplicitAny": true,
  5. "module": "es6",
  6. "target": "es5",
  7. "jsx": "react",
  8. "allowJs": true,
  9. "moduleResolution": "node",
  10. "allowSyntheticDefaultImports": true,
  11. "esModuleInterop": true,
  12. }
  13. }

如果想在 TypeScript 中保留如import _ from ‘lodash’;的语法被让它作为一种默认的导入方式,需要在文件 tsconfig.json 中设置 “allowSyntheticDefaultImports” : true 和 “esModuleInterop” : true 。

注意

1. “allowSyntheticDefaultImports”: true 配置

TypeScript 配置文件 tsconfig.json 需要加 “allowSyntheticDefaultImports”: true 配置,否则会提示 can only be default-imported using the ‘allowSyntheticDefaultImports’ flag。

  1. {
  2. "compilerOptions": {
  3. "allowSyntheticDefaultImports": true
  4. },
  5. }

不加 “allowSyntheticDefaultImports”: true 的加报错信息如下:

image.png

2. tsx 和 jsx 不能混合使用


在 tsx 中引入 jsx 文件报错如下:
image.png

以上我们完成了一个基于 webpack 编译的 SASS + TS + React 项目。

源码地址 webpack_pre_v2