背景
刚入门前端,没有搭建过大型前端项目工程,觉得模块间引用很不方便,于是研究了下
工程项目结构
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| react-ts-ui/ ├─ packages/ ├ ├─ react-components-a/ ├ ├ ├─ src/ ├ ├ ├ └─ index.tsx ├ ├ ├─ package.json ├ ├ └─ tsconfig.json ├ └─ react-components-b/ ├ ├─ src/ ├ ├ └─ index.tsx ├ ├─ package.json ├ └─ tsconfig.json ├─ src/ ├ └─ index.tsx ├─ package.json └─ tsconfig.json
|
配置
react-components-a
./packages/react-components-a/tsconfig.json
1 2 3 4 5 6
| { "compilerOptions": { "composite": true, } }
|
react-components-b
./packages/react-components-b/tsconfig.json
1 2 3 4 5 6
| { "compilerOptions": { "composite": true, } }
|
react-ts-ui
./package.json
1 2 3 4
| "private": true, "workspace": ["packages/*"]
|
./tsconfig.json
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| { "compilerOptions": { "baseUrl": "./", "paths": { "react-components-a": ["./packages/react-components-a/src"], "react-components-b": ["./packages/react-components-b/src"] } }, "references": [ { "path": "./packages/react-components-a" }, { "path": "./packages/react-components-b" } ] }
|
./webpack.config.js
1 2 3 4 5 6 7 8 9 10 11 12
| var path = require('path');
module.exports = { resolve: { alias: { 'react-components-a': path.resolve(__dirname,'packages/react-components-a/src'), 'react-components-b': path.resolve(__dirname,'packages/react-components-b/src'), } } }
|
代码
packages/react-components-a/src/index.tsx
1 2 3 4 5 6 7 8
| function componentsA() { console.log("react-components-a") }
export { componentsA }
|
packages/react-components-b/src/index.tsx
1 2 3 4 5 6 7 8
| function componentsB() { console.log("react-components-b") }
export { componentsB }
|
src/index.tsx
1 2 3 4 5
| import { componentsA } from "react-components-a"; import { componentsB } from "react-components-b";
componentsA(); componentsB();
|