【发布时间】:2022-02-19 11:51:37
【问题描述】:
我有一个简单的上下文提供程序,我想将其导出为 npm 包。
我使用 create-react-library 创建了我的 npm 包。
我创建了一个 index.tsx 文件,当从另一个项目导入这个 npm 包时可以访问该文件; 我将 Context Provider 导入到这个 index.tsx,然后将其导出。
当我尝试使用从 index.tsx 导入的 ContextProvider 运行测试时,导入的对象是 undefined(即使我可以在 VS Code 中导航到它)。但是,当我直接从源导入它时,它工作正常。我需要让它从 index.tsx 文件中运行,以便通过 npm 包访问它。
谁能向我解释一下我在这里缺少什么?
src/index.tsx
import ErrorHandler from './contexts/ErrorHandlerContextProvider'
export { ErrorHandler }
// export { default as ErrorHandler } from './contexts/ErrorHandlerContextProvider' //<-- no luck
src/index.test.tsx
// import ErrorHandler from './contexts/ErrorHandlerContextProvider' // <-- this import works
import { ErrorHandler } from '.'
describe('ErrorHandlerContextProvider', () => {
it('is truthy', () => {
expect(ErrorHandler.ErrorHandlerContextProvider).toBeTruthy()
})
})
src/contexts/ErrorHandlerContextProvider.tsx
import React, { createContext, FC, useContext } from 'react'
import PropTypes from 'prop-types'
type errorHandlerContextType = {
handleError: (error: Error, info: string) => Promise<void>
}
const ErrorHandlerContext = createContext<errorHandlerContextType | null>(null)
const useErrorHandlerContextProvider = () => {
return useContext(ErrorHandlerContext)
}
const ErrorHandlerContextProvider: FC = ({ children }) => {
const handleError = (error: Error, info: string): Promise<void> => {
console.log('error', error)
console.log('info', info)
return Promise.reject(error)
}
return (
<ErrorHandlerContext.Provider value={{ handleError }}>
{children}
</ErrorHandlerContext.Provider>
)
}
ErrorHandlerContextProvider.propTypes = {
children: PropTypes.node.isRequired
}
export default { ErrorHandlerContextProvider, useErrorHandlerContextProvider }
/tsconfig.json
{
"compilerOptions": {
"outDir": "dist",
"module": "esnext",
"lib": ["dom", "esnext"],
"moduleResolution": "node",
"jsx": "react",
"sourceMap": true,
"declaration": true,
"esModuleInterop": true,
"noImplicitReturns": true,
"noImplicitThis": true,
"noImplicitAny": true,
"strictNullChecks": true,
"suppressImplicitAnyIndexErrors": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"allowSyntheticDefaultImports": true
},
"include": ["src"],
"exclude": ["node_modules", "dist", "example"]
}
npm 运行测试
失败 src/index.test.tsx ● ErrorHandlerContextProvider › 是真实的
TypeError: Cannot read property 'ErrorHandlerContextProvider' of undefined
4 | describe('ErrorHandlerContextProvider', () => {
5 | it('is truthy', () => {
> 6 | expect(ErrorHandler.ErrorHandlerContextProvider).toBeTruthy()
| ^
7 | })
8 | })
9 |
at Object.<anonymous> (src/index.test.tsx:6:25)
【问题讨论】:
-
暂时忘记测试:TS 编译器是否成功构建了这个项目,还是因为找不到模块而崩溃?
-
tsc 运行良好,没有错误。
-
请同时发布您的 tsconfig。我想我将不得不在本地实际运行它才能弄清楚。 (如果您可以共享一个 repo 会更好,但如果这不可接受,我认为只需配置 + 已发布的代码就足够了。)
-
谢谢@Tom。回复较晚,抱歉。我已经添加了 tsconfig 以及我用来创建库的包的链接。我决定暂时使用 JS 而不是 TS,只是为了让事情顺利进行,但计划尽快让 TS 工作。再次感谢!
标签: javascript reactjs typescript npm