question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to handle an imported components imports

See original GitHub issue

Hi guys, thank you for the great project! I’m currently trying to get mdx-bundler set up with Next.js and I’m running into some issues when it comes to importing components. The imported component in the MDX file is fine but if that import has it’s own imports it throws an error. Is there a way to tacke this? I’ll show you what I have below

  • mdx-bundler version: 4.0.1
  • node version: v14.16.0
  • npm version: 6.14.11

So I have some code to prepare and get the components like in @Arcath’s post https://www.arcath.net/2021/03/mdx-bundler

import { bundleMDX } from 'mdx-bundler';
import path from 'path';
import { existsSync } from 'fs';
import { readdir, readFile } from 'fs/promises';

export const prepareMDX = async (source, files) => {
  if (process.platform === 'win32') {
    process.env.ESBUILD_BINARY_PATH = path.join(
      process.cwd(),
      'node_modules',
      'esbuild',
      'esbuild.exe'
    );
  } else {
    process.env.ESBUILD_BINARY_PATH = path.join(
      process.cwd(),
      'node_modules',
      'esbuild',
      'bin',
      'esbuild'
    );
  }

  const { code } = await bundleMDX(source, {
    files,
  });

  return code;
};

export const getComponents = async (directory) => {
  const components = {};

  if (!existsSync(directory)) return components;

  const files = await readdir(directory);

  console.log(files);

  for (const file of files) {
    if (file.substr(-3) === 'jsx') {
      const fileBuffer = await readFile(path.join(directory, file));
      components[`./components/${file}`] = fileBuffer.toString().trim();
    }
  }

  return components;
};

which allows me to import the component in postdir > componentsdir but say I am trying to import this form component

import React, { useState } from 'react';
import Button from '../../../src/components/Button';
import styles from '../form.module.css';

const FormWithStyles = ({ title }) => {
  const [content, setContent] = useState({
    subject: `Feedback sent from: ${title}`,
    email: '',
    handle: '',
    message: '',
    honeypot: '',
    accessKey: 'your-access-key',
  });

  const handleChange = (e) =>
    setContent({ ...content, [e.target.name]: e.target.value });

  return (
    <div className={styles.feedback}>
      <p>
        Please let me know if you found anything I wrote confusing, incorrect or
        outdated. Write a few words below and I will make sure to amend this
        blog post with your suggestions.
      </p>
      <form className={styles.form}>
        <label className={styles.message} htmlFor="message">
          Message
          <textarea
            name="message"
            placeholder="What should I know?"
            onChange={handleChange}
            required
          />
        </label>
        <label className={styles.email} htmlFor="email">
          Your Email (optional)
          <input type="email" name="email" onChange={handleChange} />
        </label>
        <label className={styles.handle} htmlFor="handle">
          Twitter Handle (optional)
          <input type="text" name="handle" onChange={handleChange} />
        </label>
        <input type="hidden" name="honeypot" style={{ display: 'none' }} />
        <Button className={styles.submit} type="button" text="Send Feedback" />
      </form>
    </div>
  );
};

export default FormWithStyles;

An error is thrown because the Button component is trying to be imported from my src/components directory and the styles css module is being from that same directory

This is a screenshot of the error: image

and the repo can be found here:

https://github.com/Adam-Collier/portfolio-site/tree/render_mdx

(I am currently migrating over from Gatsby so everything is a bit of a mess atm but it should be easy enough to navigate to a blog page that errors)

I appreciate any guidance you have on this and I hope you can help

Issue Analytics

  • State:open
  • Created 2 years ago
  • Comments:15

github_iconTop GitHub Comments

6reactions
city17commented, Dec 29, 2021

I’m facing the same issue where I’m trying to use a component in an MDX file, which in turn imports other components and a CSS module. So:

// This is the MDX File
import Arrow from './Arrow.jsx'

<Arrow />
// This is the component file
import { motion } from "framer-motion"
import styles from "./Arrow.module.css"

const Arrow = () => {
 return (
  <div className={styles.arrow}>➔</div>
)
}

export default Arrow

Did anyone find a definitive solution to this use case? Or is it best to use CSS in JS instead of CSS modules here? Would prefer to use modules since that’s what I’m using everywhere else on my blog…

1reaction
melosomelocommented, Apr 2, 2022

@FradSer, I opened an issue about it. I managed to make it work through some esbuild configurations, but idk if it’s a very solid solution. Waiting on a response.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Importing a Component | Create React App
We suggest that you stick to using default imports and exports when a module only exports a single thing (for example, a component)....
Read more >
Importing and Exporting Components - React Docs
Import it in the file where you'll use the component (using the corresponding technique for importing default or named exports). Here both Profile...
Read more >
Import Components in React Like a Pro - The Startup - Medium
Hello Everyone! Today I'll show you how to import components in an efficient way. This will make your code more readable and concise....
Read more >
Importing Components in React From Other Files - Upmostly
In importFrom.js, we define the function printToScreen as you'd expect, with a very simple execution. Then, we use the keyword “export” followed ...
Read more >
How to import components in React Native ? - GeeksforGeeks
And similarly, for multiple imports, we can use a comma ( , ) separator to separate two-parameter names within the curly braces. As...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found