Git Product home page Git Product logo

next-translate's Introduction

Hi, I'm Aral Roca

logo

twitter ย ย  stackoverflow ย ย  linkedin ย ย  email

I'm a Full-Stack developer who likes to work with JavaScript/Typescript (Preact, Next.js, TensorFlow.js, Node, Deno) Rust, Python among others.

Top language used in my repos
Languages used in my public repos - big fan of JavaScript ๐Ÿ˜›

A few years ago I realized that I wanted to focus my efforts on being useful. For this reason, I'm trying to contribute more and more to open-source projects, helping people on Discus, StackOverflow, Spectrum, Github discussions... and creating useful content to be used by developers: libraries and articles.


๐Ÿ“– ย ย aralroca.com: Last 5 articles


๐Ÿงก ย ย My passions


๐Ÿ‘‰ ย ย Subscribe to the newsletter

next-translate's People

Contributors

allcontributors[bot] avatar andrehsu avatar aralroca avatar bjoernrave avatar bmvantunes avatar croutonn avatar dependabot[bot] avatar dnepro avatar emmekappa avatar groomain avatar gurkerl83 avatar hichemfantar avatar j-schumann avatar luisgserrano avatar marcelotk15 avatar miikebar avatar monstrag avatar pgrimaud avatar psanlorenzo avatar rekomat avatar shunkakinoki avatar simplycomplexable avatar slevy85 avatar stlyn4 avatar testerez avatar theoludwig avatar tomvardasca avatar vimutti77 avatar vincentducorps avatar yannsuissa avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

next-translate's Issues

Global stylesheet

Hi, great library!

I'm importing a global stylesheet in page_/_app.js and the import statement is correctly copied into pages/_app.js

But next js throws the global css error

Global CSS cannot be imported from files other than your Custom <App>. Please move all global CSS imports to src/pages/_app.js.
Read more: https://err.sh/next.js/css-global
Location: src/pages_/_app.js

Any tip to solve the issue?
Thanks

Why is it necessary to use pages_ instead of normal pages?

Couldn't we just use the folder pages as the default language, then copy it into localized subfolders? We won't have to use a special "pages_" folder in that case. Also, we won't have duplicate content (pages/index.js === pages/en/index.js) for the default language.

Support for tsx files

When trying to use this lib with .tsx files it generates these imports import C from '../pages_/index.tsx' which results in this error: An import path cannot end with a '.tsx' extension. Consider importing '../pages_/index' instead.

Support polyfillsOptimization

In future next.js releases >= 9.2.3 is going to change the way that babel transpile the code, using the polyfillsOptimization by default.

I'm going to do a canary version to temporally support that if somebody wants to activate the flag experimental.polyfillsOptimization. And when 9.2.3 will be released, we are going to do a stable release.

Fix fallback when the text is not in the dictionary

Unify these fallbacks when is NO PROVIDER:

t`common:not-existent` // return an array! [ 'common:not-existent' ] (INCORRECT)
t('common:not-existent') // return an string! 'common:not-existent' (CORRECT)

to always return the fallback as the last one (as string).

Differents namespaces in the same page (with-server)

Right now we are defining the namespaces in the i18n config file as:

{
  '*': ['common'],
  '/list: ['products', 'whatever']
}

However, in some cases should be interesting that the page uses different namespaces depending on some params... To not import all the namespaces to every case.

Proposal

Allow to define namespaces as a function (only using a server, with static sites this should't be allowed).

{
  '*': ['common'],
  '/list: ({ query, req }) => query.productId ? ['products'] : ['whatever']
}

Crash if nested path is not yet defined

In case if common:first.second.third is not defined in translations files then the application just crashes in dev mode, not sure about production.
Code for it is this:
https://github.com/vinissimus/next-translate/blob/master/src/I18nProvider.js#L11

In most of the other internalization libraries if path\key is not found it just print that path and you still see and use application.
Is there some workaround this or can we create a flag which would just print non-translated path as fallback?

Typescript support

Is there a relevant @types package to download with this? I keep getting can't find module declaration or --isolatedModules error on build time (when I delcare it into @types folder)

[Question] Can you also use this for non static nextjs pages

Hi there,

I'm looking to replace our current translations setup with this package but I was wondering if you can use this without the static generation of the pages.

Can we also enhance the middleware to determine the language based upon a header that the server receives? In our current setup, we have subdomains for each locale, so there is no need for the /en, /fr, /it approach... Every subdomain has its hard-coded locale header that get's send with every request to the express server.

Looking forward to your insights and keep up the good work!

Kind regards,
Ward

[DISCUSSION] How to evolve to 1.0.0

I did a working example in the repo as an alternative to "build step", using dynamic routing.

It requires (for the moment) more configuration, but it also works for Automatic Static Optimization.

I invite you to experiment with the example that I did.

After achieving this, I'm asking myself how to evolve this library to the next major 1.0.0 release.

To be honest, I would like to remove the "build step" because it's a temporal workaround. And using dynamic routes is the natural way to achieve this in Next.js.

The problem that I see with dynamic routes is that requires three steps for each page:

  • Add lang paths to getStaticPaths
  • Add lang and namespaces props to getStaticProps
  • Add I18nProvider on top of your page. (I used a HOC in the example)

And doing this for every page can be very cumbersome.

I open this issue in order to discuss if we really want to evolve simplifying this and removing the "build step", or not. And in the case that we really want to remove the "build step", how we can simplify this to avoid this cumbersome configuration.

Any feedback will be very welcome ๐Ÿ‘


Update:

I'll remove the https://github.com/vinissimus/next-translate/tree/master/examples/with-dynamic-routes example, now there is a i18n routing support on Next.js and is a better way to evolve this library. The first step to 1.0 is the 0.19 release, adapting the i18n routing to this library.

Add tests to CLI

We have some tests of critical parts, however, in the CLI we only have 3 tests and we are not covering all the cases. I create this issue in order to improve that.

๐Ÿž| โ‰๏ธ TypeError: Cannot read property 'getInitialProps' of undefined

Issue

Whenever I am wrapping my page lets say pages_/login.tsx with a Context and Provider, I get this error.

TypeError: Cannot read property 'getInitialProps' of undefined

So the question is, how can I still be able to use my custom context and wrap my pages with without getting this error on yarn build

The error is located in here

if(C.getInitialProps) {
  Page.getInitialProps = ctx => C.getInitialProps({ ...ctx, lang: 'de'})
}

But if I add

if(C && C.getInitialProps)
....

the issue gets fixed, but this is not a since pages are dynamically created.

Support defaultLanguage as a function

It will be useful to support both types: string (current) and function (future).

The function allows putting some logic about the req. Ex:

defaultLanguage: (req) => {
 let host = req ? req.get('Host') : window.location.hostname
 return getDefaultLanguageFromHost(host)
}

Windows UnhandledPromiseRejectionWarning: Error: EPERM: operation not permitted, mkdir 'pages'

Hi,

when I restart my dev config "next-translate && next dev" in Jetbrains Webstorm i get the following Error:

(node:60144) UnhandledPromiseRejectionWarning: Error: EPERM: operation not permitted, mkdir 'pages' at Object.mkdirSync (fs.js:764:3) at createPagesDir (C:\MYAPP\node_modules\next-translate\cli\builder.js:68:6) at Object.<anonymous> (C:\MYAPP\node_modules\next-translate\cli\builder.js:53:1) at Module._compile (internal/modules/cjs/loader.js:777:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:788:10) at Module.load (internal/modules/cjs/loader.js:643:32) at Function.Module._load (internal/modules/cjs/loader.js:556:12) at Function.Module.runMain (internal/modules/cjs/loader.js:840:10) at internal/main/run_main_module.js:17:11 (node:60144) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1) (node:60144) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Of course the next server crashes, but at the next start the pages are getting created and everything works fine!

We can recreate the error on 3 Windows Machines.

Version used: 0.15.0

Ignore `/api/*` routes

In order to make this work with API routes it would be good if it could ignore that folder and just move it over as it is. Should be quick to do

next-offline

Can I use this with next-offline? Could you create an example?

Support next version 9.2.1

In the new next version 9.2.1:

ModuleNotFoundError: Module not found: Error: Can't resolve '@babel/runtime-corejs2/core-js/array/is-array'

Update content of `/api/*`

It works, that the /api routes are ignored, however the content inside there is not updated and I need to delete the folder manually.

Same applies for the _app.tsx file

Pass key with no namespace to useTranslation()?

First of all, thank you for the great work!

This example in the docs shows it's possible to pass string without namespace into useTranslation(), like so:

export default function Description() {
  const { t, lang } = useTranslation()
  const title = t('title') // instead of 'common:title' or 'home:title' etc
   // ...
}

Is this possible? What value should I pass to i18n.json and what filename should I use for the locale file?

I've also checked the example sites but this usage without namespace is not present in them.

My use case is for common translation which will be used in all pages. I've been able to use common, eg. {"*": ["common"]}, but was just wondering if that example is possible because it would be more concise.

Thanks!

Allow "*" for common namespaces declaration

Proposal for a new feature:

Alternative of:

{
  '/': ['common'],
  '/_error': ['common'],
  '/example':  ['common'],
  '/about': ['common', 'about'],
  '/contact': ['common', 'contact'],
}

Declaring * for common namespaces:

{
  '*': ['common'], // All pages 
  '/about': ['about'],
  '/contact': ['contact'],
}

[Question] Does next-translate works at Zeit Now?

Hi! Just a quick question, does the package works deploying at Zeit Now 2.0? I tried both versions, static and custom server, but couldn't get it working there (I was using an outdated next with next-translate v0.90). As I was outdated, I'm trying to upgrade it all to see if solves but it would be great if someone just says that it works (got a Internal server error there with the custom server deploy).

How does this compare to next-i18next?

Hello!

Thank you for your amazing work!

It would be interesting to have a comparison between next-translate (which looks quite new), and the more established next-i18next. What are the pros and cons of both solutions, is there a trade-off while using next-translate? etc...

Is this something you would be willing to share? ๐Ÿค—

Custom Server and Static Optimization

Hello Sirs,
Would you mind elaborating on this?

A custom server will remove important performance optimizations, like serverless functions and Automatic Static Optimization.

As I understand, is there no way to make static optimization work if I'm using next-translate with a custom server? How is using the custom server middleware different from using Next default server?

Would you please share any thoughts or updates on this matter?

Much obliged.

HTML "lang" attribute support

Hi,
is it possible to set a custom lang attribute for the html tag inside a custom _document.js, while keeping static site generation support? I think it could be fairly easy to inject it at build time in the generated html...

Don't generate pages for default locale

I've set redirectToDefaultLang to false because I want to have my default locale without language prefix in the URLs. In fact, I don't want to have my default locale callable with the language code in the URL at all.

In my opinion it's safe to assume that if redirectToDefaultLang is set to false, that a developer doesn't need generated pages for the default locale with prefix (e.g. /en/page).

If this can't be assumed from this configuration property, I would propose a new feature that makes this possible by adding a new property for it.

Steps to make it possible:

  1. (Add new configuration option)
  2. Don't generate pages pages in language code folder for default locale
  3. Don't add language prefix for default locale when Link is used

Is this something that would be merged? If so, I can look into it and open a PR.

support for windows (rm -rf)

Hello, I was trying to set up next-translate while working on windows (๐Ÿ˜… ) and it does not remove the 'pages' directory because it does not support 'rm -rf'.

Anyway. Do you think there is another way of doing what this project does, without having to change to another "pages_" structure. It seems a bit odd to change the standard way of development.

Thanks

Routing in static mode

Static mode uses URLs with the language prefix, e.g. /es/about. Thus when changing the URL, the app needs to know what the current language is. This is easily accomplished with Link, by creating a simple wrapper. Something like this:

function withLangPrefix(url, lang): string {
  if (url && url.length > 0) {
    return url.charAt(0) === '/' ? `/${lang}${url}` : `/${lang}/${url}`;
  }
  return url;
}

function Link({
  children,
  href,
  as,
  ...props
}) {
  const { lang } = useTranslation();
  return (
    <NextLink
      href={withLangPrefix(href, lang)}
      as={withLangPrefix(as, lang)}
      {...props}
    >
      {children}
    </NextLink>
  );
}

But how would we do the same when using Router.push()? Router.push() is used when you're not inside a component but need to change the URL, such as a default response to HTTP 401 responses. I thought about creating a wrapper for Router.push()

const push = (
  url,
  as,
  options
) => {
  return Router.push(withLangPrefix(url, 'en'), as, options);
};

But notice how I hardcoded the language in that example. It's because I don't know of any way to ask for the current language outside of a component. Can that be done? Is it a reasonable feature request?

Cannot export as static bundle

Hi!
First of all, awesome job you did with this library - keep it up :)

I've been playing with next for the first time, and I'm trying to build a static, localized landing page.

This is an excerpt of my next.config.js:

  exportTrailingSlash: true,
  exportPathMap: function () {
    return {
      '/': { page: '/' },
      '/documentation': { page: '/documentation' },
    };
  }

When I run next-translate && next build, the pages folder correctly includes the main pages, as well as the localized subfolders. However, if I run next export, all I get is the main pages but no localized versions. If I understand correctly, this use case should be supported. Is there a problem with the config file, where I do not export the localized pages, one by one?

Thank you!

getStaticProps is not called

I just tried to migrate from getInitialProps to getStaticProps but the new method is never called.

Just try with the documentation example to reproduce:

import fetch from 'node-fetch'

function Blog({ posts }) {
  return (
    <ul>
      {posts.map(post => (
        <li>{post.title}</li>
      ))}
    </ul>
  )
}

export async function getStaticProps() {
  console.log('Call getStaticProps')
  const res = await fetch('https://.../posts')
  const posts = await res.json()

  return {
    props: {
      posts
    }
  }
}

export default Blog

Aslo wrap _app.js with I18nProvider

In my _app file I am using a Layout component for persistent layout. The items in the layout do not get translated.

Is it maybe possible to apply the same to _app.js as you do to all other files?

[Question] - Is there a `getFixedT`?

Hello! ๐Ÿ‘‹

I started using Next JS last week and I'm amazed about how the i18n scene is still not mature yet! So thank you so much for your efforts in such a young library. It's really appreciated!

My requirement is - I want to translate an invoice to be in Arabic and English on the same page. I achieved this by using getFixedT that is provided by the i18next framework in another project.

https://www.i18next.com/overview/api#getfixedt

I understand this framework is minimal (and growing!). Can you please confirm if such a behavior is possible with this library or if you advise any workaround.

Thanks! ๐Ÿ™

Incompatible with next.js 9.3

When trying to use this lib with next.js 9.3 I get the following error:

[1] internal/modules/cjs/loader.js:796
[1]     throw err;
[1]     ^
[1] 
[1] Error: Cannot find module '@babel/runtime-corejs2/helpers/interopRequireDefault'
[1] Require stack:
[1] - /Users/bjoern/projects/inventhora/frontend/node_modules/next-translate/_helpers/getPageNamespaces.js
[1] - /Users/bjoern/projects/inventhora/frontend/node_modules/next-translate/cli/builder.js
[1]     at Function.Module._resolveFilename (internal/modules/cjs/loader.js:793:17)
[1]     at Function.Module._load (internal/modules/cjs/loader.js:686:27)
[1]     at Module.require (internal/modules/cjs/loader.js:848:19)
[1]     at require (internal/modules/cjs/helpers.js:74:18)
[1]     at Object.<anonymous> (/Users/bjoern/projects/inventhora/frontend/node_modules/next-translate/_helpers/getPageNamespaces.js:1:41)
[1]     at Module._compile (internal/modules/cjs/loader.js:955:30)
[1]     at Object.Module._extensions..js (internal/modules/cjs/loader.js:991:10)
[1]     at Module.load (internal/modules/cjs/loader.js:811:32)
[1]     at Function.Module._load (internal/modules/cjs/loader.js:723:14)
[1]     at Module.require (internal/modules/cjs/loader.js:848:19) {
[1]   code: 'MODULE_NOT_FOUND',
[1]   requireStack: [
[1]     '/Users/bjoern/projects/inventhora/frontend/node_modules/next-translate/_helpers/getPageNamespaces.js',
[1]     '/Users/bjoern/projects/inventhora/frontend/node_modules/next-translate/cli/builder.js'
[1]   ]
[1] }

JavaScript heap out of memory when building

When trying to build my application with next-translate && next build it crashes after some time because the heap is out of memory.

I have 21 pages + _document, _app and _error and three languages.

It works fine when doing next translate && next

running only next-translate first and then next build doesn't help

Version: 0.7.0
Next.js: 9.2.1

Creating an optimized production build .
<--- Last few GCs --->

[32261:0x10288c000]   276781 ms: Scavenge 2027.2 (2050.3) -> 2026.7 (2050.5) MB, 5.5 / 0.0 ms  (average mu = 0.096, current mu = 0.000) allocation failure 
[32261:0x10288c000]   276789 ms: Scavenge 2027.5 (2050.5) -> 2026.9 (2050.8) MB, 5.0 / 0.0 ms  (average mu = 0.096, current mu = 0.000) allocation failure 
[32261:0x10288c000]   277977 ms: Mark-sweep 2027.7 (2050.8) -> 2025.9 (2050.8) MB, 1186.7 / 0.0 ms  (average mu = 0.089, current mu = 0.075) allocation failure scavenge might not succeed


<--- JS stacktrace --->

==== JS stack trace =========================================

    0: ExitFrame [pc: 0x1009311f9]
    1: StubFrame [pc: 0x1008b2d21]
Security context: 0x398272e408a1 <JSObject>
    2: SourceNode_add [0x3982c547e271] [/Users/bjoern/projects/inventhora/frontend/node_modules/source-map/lib/source-node.js:~172] [pc=0x34fb321bec7e](this=0x3982116b49a1 <SourceNode map = 0x398298c8a931>,0x3982116b4841 <SourceNode map = 0x398298c8a931>)
    3: /* anonymous */ [0x3982116b4a49] [/Users/bjoern/projects/inventho...

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory

Writing Node.js report to file: report.20200213.163049.32261.0.001.json
Node.js report completed
 1: 0x10007f231 node::Abort() [/Users/bjoern/.nvm/versions/node/v12.14.1/bin/node]
 2: 0x10007f3b5 node::OnFatalError(char const*, char const*) [/Users/bjoern/.nvm/versions/node/v12.14.1/bin/node]
 3: 0x100176887 v8::Utils::ReportOOMFailure(v8::internal::Isolate*, char const*, bool) [/Users/bjoern/.nvm/versions/node/v12.14.1/bin/node]
 4: 0x100176823 v8::internal::V8::FatalProcessOutOfMemory(v8::internal::Isolate*, char const*, bool) [/Users/bjoern/.nvm/versions/node/v12.14.1/bin/node]
 5: 0x1002fa9d5 v8::internal::Heap::FatalProcessOutOfMemory(char const*) [/Users/bjoern/.nvm/versions/node/v12.14.1/bin/node]
 6: 0x1002fc0a4 v8::internal::Heap::RecomputeLimits(v8::internal::GarbageCollector) [/Users/bjoern/.nvm/versions/node/v12.14.1/bin/node]
 7: 0x1002f8f77 v8::internal::Heap::PerformGarbageCollection(v8::internal::GarbageCollector, v8::GCCallbackFlags) [/Users/bjoern/.nvm/versions/node/v12.14.1/bin/node]
 8: 0x1002f6f5d v8::internal::Heap::CollectGarbage(v8::internal::AllocationSpace, v8::internal::GarbageCollectionReason, v8::GCCallbackFlags) [/Users/bjoern/.nvm/versions/node/v12.14.1/bin/node]
 9: 0x100302674 v8::internal::Heap::AllocateRawWithLightRetry(int, v8::internal::AllocationType, v8::internal::AllocationAlignment) [/Users/bjoern/.nvm/versions/node/v12.14.1/bin/node]
10: 0x1003026ef v8::internal::Heap::AllocateRawWithRetryOrFail(int, v8::internal::AllocationType, v8::internal::AllocationAlignment) [/Users/bjoern/.nvm/versions/node/v12.14.1/bin/node]
11: 0x1002cf2e7 v8::internal::Factory::NewFillerObject(int, bool, v8::internal::AllocationType) [/Users/bjoern/.nvm/versions/node/v12.14.1/bin/node]
12: 0x1005f8935 v8::internal::Runtime_AllocateInYoungGeneration(int, unsigned long*, v8::internal::Isolate*) [/Users/bjoern/.nvm/versions/node/v12.14.1/bin/node]
13: 0x1009311f9 Builtins_CEntry_Return1_DontSaveFPRegs_ArgvOnStack_NoBuiltinExit [/Users/bjoern/.nvm/versions/node/v12.14.1/bin/node]
/bin/sh: line 1: 32261 Abort trap: 6           next build

Fix defaults

t(undefined) -> Crash
t('ns:grantfather.parent') (without child) -> Return an object instead of the fallback id.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.