shuding / nextra

Simple, powerful and flexible site generation framework with everything you love from Next.js.
https://nextra.site
MIT License
11.61k stars 1.26k forks source link

Global import for use on MDX files #3329

Open yansusanto opened 1 day ago

yansusanto commented 1 day ago
import {data, calc} from "@/components/data";

Is possible to import the above component globally for me to use {data, calc} across all .mdx files? Currently, I'm importing it at all .mdx files.

Any help is much appreciated.

dimaMachina commented 1 day ago

provide them via this option https://nextra.site/docs/docs-theme/theme-configuration#mdx-components and you will not need to import your components on every mdx file

yansusanto commented 1 day ago

That's what I did but to no avail,

import React from "react";

import {data, calc} from "@/components/data";

export default {
    main: ({children}) => {
        return (
            {children}
        );
    },
    components: {
        data,
        calc,
        Bleed,
        Cards,
        Callout,
        Steps,
        Tabs,
    },
};

Am I missing something here?

dimaMachina commented 1 day ago

Does data and calc are react component?

yansusanto commented 1 day ago

Yes, it is

export const data = {
    italy: {
        population: 1000,
    },
    america: {
        population: 2000,
    },
};

const parseNumber = (value) => {
    if (typeof value === "string") {
        return parseFloat(value.replace(/,/g, ""));
    }
    return value;
};

export const calc = (value, percentage, period = "Y") => {
    const parsedValue = parseNumber(value);
    let result = (parsedValue * percentage) / 100;

    return result.toLocaleString(undefined, {
        minimumFractionDigits: 0,
        maximumFractionDigits: 0,
    });
};
dimaMachina commented 1 day ago

They are not react components but object and function

yansusanto commented 1 day ago

You are right, it is not. I guess I have to just import it into every mdx file.

dimaMachina commented 1 day ago

You can also try to assign them to globalThis in _app file and after they will be globally accessible

yansusanto commented 1 day ago

Thank you for the pointer, @dimaMachina. You are the best!

import Inter from "@/components/font";
import "@/styles/app.scss";
import {data, calc} from "@/components/data";

export default function App({Component, pageProps}) {
    globalThis.data = data;
    globalThis.calc = calc;

    return (
        <Inter>
            <Component {...pageProps} />
        </Inter>
    );
}