Gatsby JS + Netlify + проблема загрузчика MDX - PullRequest
0 голосов
/ 27 февраля 2020

Я делаю руководство по стилю с CMS и сталкиваюсь с несколькими проблемами.

Это мой конфиг веб-пакета

exports.onCreateWebpackConfig = ({ actions }) => {
  actions.setWebpackConfig({
    plugins: [
      new WebpackNotifierPlugin({
        skipFirstNotification: true,
      }),
    ],
    resolve: {
      // Enable absolute import paths
      modules: [path.resolve(__dirname, 'src'), 'node_modules'],
      extensions: ['.js', '.jsx', '.json', '.tsx'],
    },
  })
}

Это мой пакет. json

    "@babel/core": "^7.2.2",
    "@material-ui/core": "^4.9.1",
    "@material-ui/icons": "^4.9.1",
    "@mdx-js/mdx": "^0.16.8",
    "@mdx-js/tag": "^0.16.6",
    "@reach/router": "^1.2.1",
    "@typescript-eslint/parser": "^2.19.0",
    "d3-ease": "^1.0.5",
    "docz-utils": "^0.13.6",
    "gatsby": "^2.0.76",
    "gatsby-image": "^2.0.20",
    "gatsby-link": "^2.2.29",
    "gatsby-mdx": "^0.3.4",
    "gatsby-plugin-catch-links": "^2.0.9",
    "gatsby-plugin-manifest": "^2.0.9",
    "gatsby-plugin-mdx": "^1.0.67",
    "gatsby-plugin-netlify-cms": "4.1.40",
    "gatsby-plugin-offline": "^2.0.16",
    "gatsby-plugin-sharp": "^2.0.14",
    "gatsby-react-router-scroll": "^2.1.21",
    "gatsby-source-filesystem": "^2.0.16",
    "gatsby-transformer-sharp": "^2.1.8",
    "hast-util-to-string": "^1.0.1",
    "jss": "^10.0.4",
    "jsx-to-string": "^1.4.0",
    "lodash": "^4.17.11",
    "marked": "^0.6.0",
    "netlify-cms-app": "2.9.1",
    "netlify-cms-widget-mdx": "^0.4.3",
    "netlify-identity-widget": "^1.5.6",
    "prismjs": "^1.15.0",
    "prop-types": "^15.6.2",
    "react": "^16.8.0",
    "react-dom": "^16.8.0",
    "react-head": "^3.0.2",
    "react-highlight": "^0.12.0",
    "react-powerplug": "^1.0.0",
    "styled-system": "^3.2.1",
    "unstated": "^2.1.1",
    "write": "^1.0.3"

Это мой компонент:

interface IButtons {
  children: React.ReactElement;
}

const useStyles = makeStyles({
  root: {

  },
  button: {
    display: 'flex',
    justifyContent: 'space-between' as 'space-between',
    padding: `16px 8px`,
    paddingRight: '50px',
    background: `#F7F9FE`,
    position: 'relative' as 'relative'
  },
  expand: {
    position: 'absolute' as 'absolute',
    top: 0,
    right: 0,
    cursor: 'pointer'
  },
  code: {
    padding: `16px`,
    fontSize: `14px`
  }
});

const Buttons = (props: IButtons) => {
  const classes = useStyles();
  const [isCodeOpen, setCode] = useState(false)
  const children = React.Children.toArray(props.children)

  const stringChildren = useMemo(() => {
    let stringed: string[] | string = []

    for (let i = 0; i < React.Children.count(children); i++) {
      stringed
        .push(jsxToString(props.children[i])
        .replace('WithStyles(ForwardRef(Button))', 'Button')
        .replace('/WithStyles(ForwardRef(Button))', '/Button'))
    }

    return stringed.join("\n\n")
  }, [props.children])

  return (
    <section className={classes.root}>
      <div className={classes.button}>
        <CodeIcon className={classes.expand} fontSize='small' onClick={() => setCode(!isCodeOpen)}></CodeIcon>
        {props.children}
      </div>
      {isCodeOpen && 
        <Highlight language="javascript" className={classes.code}>
            {stringChildren}
        </Highlight>} 
    </section>
  )
}

И это мои компоненты пользовательского интерфейса

export const UIComponents = {
  ...UI,
  DeleteIcon,
  Buttons,
  // TODO: include additional custom components here, eg:
  Janky: props => <UI.TextField {...props} placeholder={'janky'} />
}

И мой запрос

{
      resolve: "gatsby-mdx",
      options: {
        extensions: [".mdx", ".md"],
        defaultLayouts: {
          default: require.resolve("./src/components/Layout/index.tsx"),
        },
        globalScope: `
          import { UIComponents } from 'Theme'
          export default {
            ...UIComponents
          }
        `,

        // mdPlugins: [],
        // gatsbyRemarkPlugins: [{}],
      },
    },

Первая проблема, с которой я сталкиваюсь при запуске приложения, - это сообщение об ошибке. Я не уверен, какие загрузчики мне нужно установить.

Module parse failed: The keyword 'interface' is reserved (8:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| import jsxToString from 'jsx-to-string';
|
> interface IButtons {
|   children: React.ReactElement;
| }

 @ ./src/Theme.jsx 32:0-43 123:11-18
 @ ./src/cms/cms.jsx
 @ multi ./node_modules/gatsby-plugin-netlify-cms/cms.js ./src/cms/cms

Вторая проблема заключается в том, что в моем превью netlify cms я получаю:

Invalid MDX:
ReferenceError: Buttons is not defined

Даже если в самом приложении есть кнопки Компонент рендеринга, в предварительном просмотре это не так.

1 Ответ

1 голос
/ 27 февраля 2020

Gatsby не поставляется с поддержкой Typescript из коробки, но вы можете легко добавить ее с помощью плагина gatsby-plugin-typescript .

Установить

npm install gatsby-plugin-typescript

Как использовать

  1. Включить плагин в файл gatsby-config. js.
  2. Напишите ваши компоненты в TSX или TypeScript.
  3. Вы хороши для go.

gatsby-config. js

module.exports = {
  // ...,
  plugins: [`gatsby-plugin-typescript`],
}
...