2

这是一个 next.js SSG 项目,但是在npm run dev尝试import react-markdown. 我无法通过这一步进行测试next export

我知道 react-markdown 是一个 esm 包,但我不清楚如何将 esm 导入我的不是 esm 的项目中。我缺少任何包裹吗?我没有使用顺风 css。

对此的任何帮助将不胜感激。

Server Error
Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

This error happened while generating the page. Any console logs will be displayed in the terminal window.
Call Stack
ReactDOMServerRenderer.render

包.json

{
  "browserslist": [
    ...
  ],
  "dependencies": {
    "autoprefixer": "^10.3.6",
    "axios": "^0.21.4",
    "next": "^11.1.2",
    "postcss-flexbugs-fixes": "^5.0.2",
    "postcss-normalize": "^10.0.1",
    "postcss-preset-env": "^6.7.0",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-markdown": "^7.1.0",
    "swr": "^1.0.1"
  },
  "devDependencies": {
    "@types/jest": "^27.0.2",
    "@types/react": "^17.0.25",
    "babel-jest": "^27.2.4",
    "express": "^4.17.1",
    "jest": "^27.3.1",
    "typescript": "^4.4.2"
  },
  "engines": {
    "node": ">=14.17.6",
    "npm": ">=6.14.15"
  },
  "name": "...",
  "private": true,
  "scripts": {
    "dev": "cross-env NODE_OPTIONS='--inspect' NODE_ENV='development' node server.js",
    "export": "next export",
    "start": "next start",
    "test": "jest",
  },
  "version": "0.1.0"
}

next.config.js

module.exports = {
  ...
  experimental: {
    esmExternals: true, //also tried 'loose'
  }
  ...
};

tsconfig.json

{
  "compilerOptions": {
    "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "baseUrl": ".",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "lib": ["dom", "dom.iterable", "esnext"],
    "module": "esnext",
    "moduleResolution": "node",
    "noEmit": true,
    "downlevelIteration": true,
    "resolveJsonModule": true,
    "skipLibCheck": true,
    "strict": false,
    "target": "es5"
  },
  "exclude": ["node_modules"],
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"]
}

零件

import React from 'react';
import ReactMarkdown from 'react-markdown';

type TestComponentProps = {
  summaryTitle: string;
  markdownString: string;
};

export const TestComponent = ({ summaryTitle, markdownString }: TestComponentProps): JSX.Element => {
  return (
    <div className="container">
      <h2 id="ratingsId">
        {summaryTitle}
      </h2>
      <p>{markdownString}</p>
      <ReactMarkdown>{markdownString}</ReactMarkdown>
    </div>
  );
};
4

1 回答 1

1

您需要强制ReactMarkdown在客户端运行

const ReactMarkdown= dynamic(() => import('react-markdown'),{ ssr: false })
于 2021-10-28T04:41:03.453 回答