Я не могу импортировать именованные экспорты из созданной мной внешней библиотеки компонентов, как описано в официальной документации . Ситуация кажется очень нишевой, так как я изо всех сил пытаюсь найти в Интернете что-нибудь, что приблизило бы меня к решению. Кому-нибудь удалось заставить его работать?
А вот и контекст ...
В моей NPM библиотеке
Компонент
Модальный компонент (фрагмент)
const Modal: React.FC<ModalProps> = ({ onCancelCallback, children }) => {...};
export default Modal;
Как видите, я экспортирую его как файл по умолчанию из Modal.tsx, но позже реэкспортирую его как именованный экспорт в файл index.ts каждой папки, например Итак:
export { default as Modal } from './Modal';
, затем
export { Modal } from './Modal';
и, наконец:
export * from './components';
Интерфейс
ModalProps
export interface ModalProps {
onCancelCallback?: () => void;
}
In Next. js
Вот как я импортирую свой внешний «модальный» компонент в один из компонентов Next. js (не страниц):
nextjscomponent.tsx
import dynamic from 'next/dynamic';
const Modal = dynamic(() => import('my-ui-kit').then((mod) => mod.Modal), {
ssr: false,
});
Ошибка ввода
Argument of type '() => Promise<React.ComponentClass<never, any> | React.FunctionComponent<never> | { default: React.ComponentType<never>; } | React.FC<ModalProps>>' is not assignable to parameter of type 'DynamicOptions<{}> | (() => LoaderComponent<{}>) | LoaderComponent<{}>'.
Type '() => Promise<React.ComponentClass<never, any> | React.FunctionComponent<never> | { default: React.ComponentType<never>; } | React.FC<ModalProps>>' is not assignable to type '() => LoaderComponent<{}>'.
Type 'Promise<ComponentClass<never, any> | FunctionComponent<never> | { default: ComponentType<never>; } | FC<ModalProps>>' is not assignable to type 'LoaderComponent<{}>'.
Type 'ComponentClass<never, any> | FunctionComponent<never> | { default: ComponentType<never>; } | FC<ModalProps>' is not assignable to type 'ComponentClass<{}, any> | FunctionComponent<{}> | { default: ComponentType<{}>; }'.
Type 'ComponentClass<never, any>' is not assignable to type 'ComponentClass<{}, any> | FunctionComponent<{}> | { default: ComponentType<{}>; }'.
Type 'ComponentClass<never, any>' is not assignable to type 'ComponentClass<{}, any>'.
Types of property 'getDerivedStateFromProps' are incompatible.
Type 'GetDerivedStateFromProps<never, any> | undefined' is not assignable to type 'GetDerivedStateFromProps<{}, any> | undefined'.
Type 'GetDerivedStateFromProps<never, any>' is not assignable to type 'GetDerivedStateFromProps<{}, any>'.
Types of parameters 'nextProps' and 'nextProps' are incompatible.
Type 'Readonly<{}>' is not assignable to type 'never'.ts(2345)
Примечания
- Я Использование Rollup для переноса содержимого папки «sr c» с компонентом и индексных файлов в папку «dist», которая заканчивается индексом. cjs. js (для Common JS), index. esm. js (для модулей ES) и куча автоматически сгенерированных .d .ts файлы.
- Я использую ссылку Yarn для проверки интеграции моей внешней библиотеки в мой проект Next. js локально.
Любая помощь очень важна. Заранее спасибо.
Обновление от 4 апреля 2020 года
На официальной странице GitHub в Next. js Мне сказали, что проблема может быть связана с фактом. что две библиотеки @ types / реагируют одновременно в одном проекте Next. js.
Вот что я попытался (безрезультатно) проверить эту гипотезу:
Я быстро проверил «пряжу почему @ types / реагировать» и увидел следующее:
yarn why v1.22.4
[1/4] ? Why do we have the module "@types/react"...?
[2/4] ? Initialising dependency graph...
[3/4] ? Finding dependency...
[4/4] ? Calculating file sizes...
=> Found "@types/react@16.9.32"
info Has been hoisted to "@types/react"
info This module exists because it's specified in "devDependencies".
info Disk size without dependencies: "164KB"
info Disk size with unique dependencies: "1.98MB"
info Disk size with transitive dependencies: "1.98MB"
info Number of shared dependencies: 2
=> Found "@types/react-dom#@types/react@16.9.31"
info This module exists because "@types#react-dom" depends on it.
info Disk size without dependencies: "164KB"
info Disk size with unique dependencies: "1.98MB"
info Disk size with transitive dependencies: "1.98MB"
info Number of shared dependencies: 2
✨ Done in 0.99s.
Затем я попробовал три вещи:
- Отключить мою библиотеку> очистить кэш пряжи> переустановить библиотека (на этот раз из недавно созданного архива tgz). Проблема сохранилась
- Пряжа удалить @ types / реагировать из папки Next. js (фактически оставив только @ types / реагировать v16.9.31 поднятым из @ types / реагировать на dom). Проблема сохранилась
- Полностью удалил node_modules и yarn.lock и переустановил все пакеты (включая мою библиотеку из архива). Проблема не исчезла.
Я все еще вижу то же сообщение об ошибке.
Кстати, этот же компонент отлично работает с динамической c загрузкой при импорте из Next. js собственная папка компонентов проекта, но цель, очевидно, в том, чтобы использовать внешний интерфейс UI.