一次解決React+TypeScript+Webpack 別名(alias)找不到問題的過程「轉載」

連接css

引言

在組件開發中,業務功能和基礎組件通常分開放,好比在咱們的項目中,components爲基礎組件, container爲業務組件,可是在container中調用components中的組件時,必須經過相對路徑如../../components/XXXX才能找到要用的基礎組件,這裏 ../../在開發時其實時一種浪費。爲了解決這個問題,咱們引入了webpack.resolve.alias功能。html

目錄結構

├── package.json ├── postcss.config.js ├── public │ ├── favicon.ico │ ├── index.html │ └── template.html ├── README.md ├── src │ ├── components │ ├── config.ts │ ├── container │ ├── index.scss │ ├── index.tsx │ ├── README.md │ ├── routers.tsx │ ├── stories │ ├── @types │ └── utils ├── styleguide.config.js ├── tsconfig.json ├── tslint.json ├── webpack.config.js ├── webpack.doc.js ├── webpack.vendor.js └── yarn.lock

 

  

 

webpack 配置

// ...
resolve: { extensions: ['.ts', '.tsx', '.js', 'config.js', '.json'], alias: { '@components': path.resolve(__dirname, './src/components'), '@container': path.resolve(__dirname, './src/container'), '@utils': path.resolve(__dirname, './src/utils'), '@stories': path.resolve(__dirname, './src/stories') } }, // ...

 

經過上述配置,webpack已經沒問題,再將代碼中全部關於調用這些components、container、utils和stories的代碼進行簡化,示例以下webpack

以前

// ./src/test/index.tsx
import AjaxTest from '../../components/Ajax'

 

以後

// ./src/test/index.tsx
import AjaxTest from '@components/Ajax'

 

問題1 [tslint] Module '@components/Ajax' is not listed as dependency in package.json (no-implicit-dependencies)

由於ts項目用了tslint來規約代碼,因此會報錯,查看官網關於no-implicit-dependencies的說明,將tslint.json增長以下規則git

{ ...... "rules": { ...... "no-implicit-dependencies": ["optional", ["src"]] } , ...... }

 

問題2 "no-implicit-dependencies": ["optional", ["src"]]

一看時ts報錯,確定時編譯環境有問題,查看官網關於paths的定義,paths主要用來作目錄映射,shangma上面webpack解決的時打包過程當中的映射,並無解決ts編譯時的映射,因此在tsconfig.json中增長一項映射信息github

{ "compilerOptions": { "baseUrl": ".", ...... "paths": { "@components/*": ["./src/components/*"], "@container/*": ["./src/container/*"], "@utils/*": ["./src/utils"], "@stories/*": ["./src/stories"] }, ...... }, ...... }
相關文章
相關標籤/搜索