在React App中使用TS开发自定义模块



我有两个具有通用功能的项目。

我需要开发我自己的npm模块,该模块将使用通用代码片段。

我做了一个单独的项目,将包含这个共享代码(例如util(。

目前,我已完成以下工作:我们有3个项目:项目-a工程-b前端组件

我正在发布一个">前部组件";我们公司npm中的项目。然后,我只将其作为依赖项包含在package.json中的其余项目中

为了在本地开发这个模块,我做了以下工作:

  1. 我将所需项目中的node_modules文件夹复制到">前部组件";

    在/项目a/node_modules/节点模块

  2. 项目生成npm链接

    npm链接/前端组件

  3. 的发展

但现在我在配置tsconfig.json时遇到了困难

例如,在">前部组件";有这样的代码:

import { DATE_FORMAT } from 'constants/date';

我得到一个错误:

Module not found: Can't resolve 'constants/date' in '..../front-components/src/hooks'

我认为问题出现在tsconfig.json中,但我不明白为什么会发生这种情况。

问题1:我可以使用其他方法来避免将node_modules复制到">前部组件";?(我需要文件是.ts和.tsx格式,而不是d.ts(

问题2:如何解决进口问题?

附言:也许你对如何开发这种捆绑包有一些建议,我会感谢

tsconfig.json

{
"compilerOptions": {
/* Basic Options */
"target": "es6", // Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'.
"module": "esnext", // Specify library files to be included in the compilation.
"lib": [
// Specify library files to be included in the compilation.
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true, // Allow javascript files to be compiled
"jsx": "react-jsx", // Generates corresponding '.d.ts' file.
"noEmit": true, // Do not emit outputs.
"isolatedModules": true, // Transpile each file as a separate module (similar to 'ts.transpileModule').
/* Strict Type-Checking Options */
"strict": true, // Enable all strict type-checking options.
/* Additional Checks */
"noFallthroughCasesInSwitch": true, // Report errors for fallthrough cases in switch statement.
"noUncheckedIndexedAccess": true, // Include 'undefined' in index signature results.
/* Module Resolution Options */
"moduleResolution": "node", // Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6).
"baseUrl": "src", // Base directory to resolve non-absolute module names.
"allowSyntheticDefaultImports": true, // Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'.
"esModuleInterop": true, // Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'.
/* Advanced Options */
"skipLibCheck": true, // Skip type checking of declaration files.
"forceConsistentCasingInFileNames": true, // Disallow inconsistently-cased references to the same file.
"resolveJsonModule": true
},
"include": ["src", "./global.d.ts"],
"files": ["node_modules/front-components/src/index.ts"],
"exclude": ["node_modules"]
}

由于两个项目都依赖于相同的UI组件,所以听起来您需要的是monorepo。它以您需要的方式为您提供了依赖关系管理的灵活性(目前的方法似乎过于复杂,效率不高(。根据你使用的包管理器,你可以选择它的方法。我的意思不是说你必须换成纱线浆果,这只是一个非常简约的例子,让你对单回购有一个深刻的想法。我个人的偏好是Nx,所以在谷歌上搜索更多信息和好运,享受编码吧!

最新更新