Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

⨯ TypeError: (0 , react__WEBPACK_IMPORTED_MODULE_0__.createContext) is not a function #2295

Open
SABEYGUNA opened this issue Aug 30, 2024 · 10 comments

Comments

@SABEYGUNA
Copy link

Getting above error in new app created with latest Next version.

⨯ TypeError: (0 , react__WEBPACK_IMPORTED_MODULE_0__.createContext) is not a function at eval (webpack-internal:///(rsc)/./node_modules/react-i18next/dist/es/context.js:22:73) at (rsc)/./node_modules/react-i18next/dist/es/context.js (D:\Sankalpa\Personal\blog\NextJs-Translation\nextjs_translation\.next\server\vendor-chunks\react-i18next.js:60:1) at __webpack_require__ (D:\Sankalpa\Personal\blog\NextJs-Translation\nextjs_translation\.next\server\webpack-runtime.js:33:42) at eval (webpack-internal:///(rsc)/./node_modules/react-i18next/dist/es/Trans.js:8:69) at (rsc)/./node_modules/react-i18next/dist/es/Trans.js (D:\Sankalpa\Personal\blog\NextJs-Translation\nextjs_translation\.next\server\vendor-chunks\react-i18next.js:30:1) at __webpack_require__ (D:\Sankalpa\Personal\blog\NextJs-Translation\nextjs_translation\.next\server\webpack-runtime.js:33:42) at eval (webpack-internal:///(rsc)/./node_modules/react-i18next/dist/es/index.js:26:67) at (rsc)/./node_modules/react-i18next/dist/es/index.js (D:\Sankalpa\Personal\blog\NextJs-Translation\nextjs_translation\.next\server\vendor-chunks\react-i18next.js:90:1) at __webpack_require__ (D:\Sankalpa\Personal\blog\NextJs-Translation\nextjs_translation\.next\server\webpack-runtime.js:33:42) at eval (webpack-internal:///(rsc)/./node_modules/next-i18next/dist/esm/index.js:11:71) at (rsc)/./node_modules/next-i18next/dist/esm/index.js (D:\Sankalpa\Personal\blog\NextJs-Translation\nextjs_translation\.next\server\vendor-chunks\next-i18next.js:60:1) at __webpack_require__ (D:\Sankalpa\Personal\blog\NextJs-Translation\nextjs_translation\.next\server\webpack-runtime.js:33:42) at eval (webpack-internal:///(rsc)/./app/page.tsx:7:70) at (rsc)/./app/page.tsx (D:\Sankalpa\Personal\blog\NextJs-Translation\nextjs_translation\.next\server\app\page.js:195:1) at Function.__webpack_require__ (D:\Sankalpa\Personal\blog\NextJs-Translation\nextjs_translation\.next\server\webpack-runtime.js:33:42) at async e9 (D:\Sankalpa\Personal\blog\NextJs-Translation\nextjs_translation\node_modules\next\dist\compiled\next-server\app-page.runtime.dev.js:35:396476) at async tb (D:\Sankalpa\Personal\blog\NextJs-Translation\nextjs_translation\node_modules\next\dist\compiled\next-server\app-page.runtime.dev.js:35:400134) at async tS (D:\Sankalpa\Personal\blog\NextJs-Translation\nextjs_translation\node_modules\next\dist\compiled\next-server\app-page.runtime.dev.js:35:400695) at async tS (D:\Sankalpa\Personal\blog\NextJs-Translation\nextjs_translation\node_modules\next\dist\compiled\next-server\app-page.runtime.dev.js:35:400826) at async tR (D:\Sankalpa\Personal\blog\NextJs-Translation\nextjs_translation\node_modules\next\dist\compiled\next-server\app-page.runtime.dev.js:36:2130) at async D:\Sankalpa\Personal\blog\NextJs-Translation\nextjs_translation\node_modules\next\dist\compiled\next-server\app-page.runtime.dev.js:36:2722 { digest: '3222498571', page: '/'

Package.json
{ "name": "nextjs_translation", "version": "0.1.0", "private": true, "scripts": { "dev": "next dev", "build": "next build", "start": "next start", "lint": "next lint" }, "dependencies": { "i18next": "^23.14.0", "next": "14.2.7", "next-i18next": "^15.3.1", "react": "^18", "react-dom": "^18", "react-i18next": "^15.0.1" }, "devDependencies": { "@types/node": "^20", "@types/react": "^18", "@types/react-dom": "^18", "eslint": "^8", "eslint-config-next": "14.2.7", "postcss": "^8", "tailwindcss": "^3.4.1", "typescript": "^5" } }

@adrai
Copy link
Member

adrai commented Aug 31, 2024

sorry, not able to reproduce...
just updated the Next.js dependencies in this example and it still works: https://github.com/i18next/next-i18next/tree/master/examples/simple

@skysteve
Copy link

skysteve commented Sep 3, 2024

if you're using app router this package doesn't work per readme:

If you're using Next.js 13/14 with app directory, there is no need for next-i18next, you can directly use i18next and react-i18next, like described in this blog post.

@krystiankulik
Copy link

That's right, the library doesn't work with the app router. I think it should be written down in the README in a more direct way because "there is no need" is bit confusing.

@georgehgfonseca
Copy link

if you're using app router this package doesn't work per readme:

If you're using Next.js 13/14 with app directory, there is no need for next-i18next, you can directly use i18next and react-i18next, like described in this blog post.

This worked but the solution is quite ugly and verbose when compared to i18n in standalone React..

@weiqiangChow
Copy link

if you're using app router this package doesn't work per readme:

If you're using Next.js 13/14 with app directory, there is no need for next-i18next, you can directly use i18next and react-i18next, like described in this blog post.

This worked but the solution is quite ugly and verbose when compared to i18n in standalone React..

bro,
Are there any other solutions out there? this solution is ugliest...
when i need multiple languages, It will make my project very bloated

@adrai
Copy link
Member

adrai commented Oct 16, 2024

when i need multiple languages, It will make my project very bloated

why do you say it will make it very bloated? the folder structure does not increase when addiing more and more languages... it's always the same... only the translation json files needs to be there...

@weiqiangChow
Copy link

sorry. I misunderstood it.👀

@CryptoNinja0331
Copy link

Sorry, could you plz say in other way?

@RampantDespair
Copy link

if you're using app router this package doesn't work per readme:

If you're using Next.js 13/14 with app directory, there is no need for next-i18next, you can directly use i18next and react-i18next, like described in this blog post.

Then perhaps this should be updated : https://github.com/i18next/react-i18next/tree/v9.x.x/example/nextjs .
Because react-i18next sends me here.

@zezang
Copy link

zezang commented Dec 6, 2024

Hi, I'm running into a similar issue. My setup is a bit complex because I have some specific requirements.

We only bundle the default language translation files with the app. For all other locales, I need to send a request to our server to get a url to the translation file. Additionally, I only want to load the translation file for the default namespace initially, and lazy load the other two namespaces once a page that needs their translations is visited. As a result I've chained together three backend, with the first serving the default load path, the second uses the resourcesToBackend utility, and the third makes the fetch requests for all other namespace/locale combinations.

Here is my next-i18next.config.mjs file:

import I18NextHttpBackend from "i18next-http-backend/cjs";
import { initReactI18next } from "react-i18next";
import ChainedBackend from "i18next-chained-backend";
import resourcesToBackend from "i18next-resources-to-backend";

const DEFAULT_PUBLIC_LOAD_PATH = "/translations/generated/{{lng}}/{{ns}}.json";

const isServer = typeof window === typeof undefined;

export const DEFAULT_LANGUAGE = "en";
const SUPPORTED_LANGUAGES = [
    "en",
    "zh-CN",
    "zh-TW",
    "cs",
    "nl",
    "fr",
    "de",
];

const DEFAULT_NAMESPACE = "public";
const NAMESPACES = ["public", "ns1", "ns2"];

export const parseQuery = (search) => {
  // Parse boolean strings into booleans.
  return queryString.parse(search, { parseBooleans: true });
};

const getLanguageFromPathAndQuery = () => {
  let lng = DEFAULT_LANGUAGE;

  if (!isServer) {
    const pathSegments = window.location.pathname.split('/');
    if (SUPPORTED_LANGUAGES.includes(pathSegments[1])) {
      lng = pathSegments[1];
      return lng;
    }

    const queryParams = parseQuery(window.location.search);
    if (queryParams.language && SUPPORTED_LANGUAGES.includes(queryParams.language)) {
      lng = queryParams.language;
    }
  }

  return lng;
};

const languageDetector = {
  type: "languageDetector",
  async: true,
  detect: (callback) => {
    const lng = getLanguageFromPathAndQuery();
    callback(lng);
  },
};

const getBackends = () => {
  console.log("getBackends isServer", isServer);
  if (isServer) {
    return [];
  }

  return [
    // first backend - used for loading public english translation files
    I18NextHttpBackend,
    //lazy-loading english translation files from non-public namespaces
    resourcesToBackend(async (language, namespace) => {
      if (language !== DEFAULT_LANGUAGE || namespace == DEFAULT_NAMESPACE) {
        return Promise.reject();
      }  
      const filePath = `./${namespace}/translations/generated/${language}/translation.json`;
      try {
        const module = await import(filePath, { assert: { type: "json" } });
        return module.default || module;
      } catch (e) {
        console.error(`Failed to load translation file for language: ${language} and namespace: ${namespace}: ${e}`);
        throw e;
      }
    }),
    I18NextHttpBackend,
  ];
}

const BACKEND_OPTIONS = [
  { loadPath: DEFAULT_PUBLIC_LOAD_PATH },
  {},
  {
    loadPath: async (language, namespace) => {
      console.log(`Loading translation file from server for language: ${language} and namespace: ${namespace}`);
      let translationsPath = DEFAULT_PUBLIC_LOAD_PATH;

      try {
        const url = "https://myApp.com/platform/translationFileUrl"
        const payload = {
            lang: language,
            namespaces: [namespace],
        }

        const response = await fetch(url, {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                "Accept": "application/json",
            },
            body: JSON.stringify(payload),
        });

        if (!response.ok) {
            console.error(`Failed to load public translation file URL for lang: ${language}: ${response.statusText}`);
            return translationsPath;
        }

        const translationFileUrls = await response.json();
        console.log("trnaslationFileUrls", translationFileUrls);
        if (translationFileUrls.length === 0) {
            console.error(`No public translation file URLs found for lang: ${language} and namespace: ${namespace}`);
            return translationsPath;
        }

        const translationFileUrl = translationFileUrls[0];
        return translationFileUrl.url;
      } catch (e) {
        console.error(`Failed to load public translation file URL for lang: ${language}: ${e}`);
        return translationsPath;
      }
    },
  },
];

/** @type {import('next-i18next').UserConfig} */
const config = {
  i18n: {
    locales: SUPPORTED_LANGUAGES,
    defaultLocale: 'en',
  },
  ns: NAMESPACES,
  defaultNS: DEFAULT_NAMESPACE,
  fallbackLng: {
    default: DEFAULT_LANGUAGE
  },
  backend: {
    backends: getBackends(),
    backendOptions: BACKEND_OPTIONS,
  },
  serializeConfig: false,
  use: isServer ? [] : [languageDetector, ChainedBackend, initReactI18next],
};

export default config;

This is the root of our Next.js application:

import {RootCMSClient} from '@blinkk/root-cms'
import {cmsPlugin} from '@blinkk/root-cms/plugin'
import React from 'react'

import { appWithTranslation } from 'next-i18next'

import type {PagesDoc} from 'root-cms-site'

import {PageModules} from '@/common/axiom/components/PageModules/PageModules'
import config from '@/../next-i18next.config.mjs'

import styles from './page.module.scss'

const Page = async () => {
  let newsContent = <div>Loading...</div>

  try {
    const cmsClient = new RootCMSClient({
      rootDir: '',
      plugins: [
        cmsPlugin({
          watch: false,
          id: process.env.ROOT_CMS_PLUGIN_ID,
          firebaseConfig: {
            apiKey: process.env.ROOT_CMS_PLUGIN_API_KEY,
            authDomain: process.env.ROOT_CMS_PLUGIN_FIREBASE_AUTH_DOMAIN,
            projectId: process.env.ROOT_CMS_PLUGIN_FIREBASE_PROJECT_ID,
            storageBucket: process.env.ROOT_CMS_PLUGIN_FIREBASE_STORAGE_BUCKET,
            messagingSenderId:
              process.env.ROOT_CMS_PLUGIN_FIREBASE_MESSAGING_SENDER_ID,
            appId: process.env.ROOT_CMS_PLUGIN_FIREBASE_APP_ID,
          },
        }),
      ],
    })

    const doc: PagesDoc = await cmsClient.getDoc('Pages', 'sandbox', {
      mode: 'published',
    })
    const {modules} = doc.fields.content

    newsContent = <PageModules modules={modules} />
  } catch (error) {
    // eslint-disable-next-line no-console
    console.error(error)

    newsContent = <div>Failed to load</div>
  }

  return (
    <div className={styles.root}>
      <div>
        <div className={styles.sectionTitle}>Latest News</div>
        <div>{newsContent}</div>
      </div>
    </div>
  )
}

export default appWithTranslation(Page, config);

I get the following error when trying to run the app locally:

TypeError: (0 , react__WEBPACK_IMPORTED_MODULE_0__.createContext) is not a function at __webpack_require__ (/Users/oz/apps/myProject/platform/frontend/.next/server/webpack-runtime.js:33:42) at __webpack_require__ (/Users/oz/apps/myProject/platform/frontend/.next/server/webpack-runtime.js:33:42) at __webpack_require__ (/Users/oz/apps/myProject/platform/frontend/.next/server/webpack-runtime.js:33:42) at eval (./next-i18next.config.mjs:8:71) at (rsc)/./next-i18next.config.mjs (/Users/oz/apps/myProject/platform/frontend/.next/server/app/page.js:781:1) at __webpack_require__ (/Users/oz/apps/myProject/platform/frontend/.next/server/webpack-runtime.js:33:42) at eval (./src/app/page.tsx:14:82) at __webpack_require__.a (/Users/oz/apps/myProject/platform/frontend.next/server/webpack-runtime.js:100:13) at eval (./src/app/page.tsx:1:21) at (rsc)/./src/app/page.tsx (/Users/oz/apps/myProject/platform/frontend/.next/server/app/page.js:509:1) at Function.__webpack_require__ (/Users/oz/apps/myProject/platform/frontend/.next/server/webpack-runtime.js:33:42) at async Promise.all (index 0)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

9 participants