Code Splitting
Code splitting is a technique that allows developers to split their application code into smaller, more manageable pieces. It's commonly used to enhance the performance of web applications by loading only the necessary code when it's needed. Terai takes a similar approach to code splitting for translation messages.
The code splitting strategies in Terai offer several key benefits:
- Efficient Loading: By splitting translation messages, Terai ensures that users benefit from efficient loading. They only load the translation messages that are necessary for the specific part of the application they are using. This significantly reduces the initial load time and makes the application more responsive.
- Reduced Network Traffic: With code splitting, your application sends fewer translation messages over the network, leading to reduced data transfer. This can be especially important for users on slower or limited network connections.
- Improved User Experience: By loading only the necessary translations, you provide users with a better experience. They don't have to wait for unnecessary translations to load, and the application remains responsive and snappy.
Usage
When creating an instance of getTs
(or using useTs
in React), you have the
option to designate the specific chunk to which the messages associated with
that instance are linked.
import { useTs } from '@terai/react'
export function Button() {
const { ts } = useTs({ chunkId: 'button' })
return (
<div>
<p>{ts`This message will be part of the "button" chunk`}</p>
<p>{ts`This message also will be part of the "button" chunk`}</p>
</div>
)
}
You have the flexibility to utilize chunk IDs throughout your entire application, simplifying the process of defining chunks according to your specific requirements.
import { useTs } from '@terai/react'
export function Header() {
const { ts } = useTs({ chunkId: 'common' })
return (
<div>
<p>{ts`A message in the header`}</p>
</div>
)
}
import { useTs } from '@terai/react'
export function Footer() {
const { ts } = useTs({ chunkId: 'common' })
return (
<div>
<p>{ts`A message in the footer`}</p>
</div>
)
}
That’s it. Terai ensures that only the translation messages relevant to that instance are loaded, automatically loading the required code chunk for the file. This means you don't have to manually manage code splitting for individual translation message files.
Known limitations
The current static extraction process in Terai does not involve code
execution, which means it cannot utilize dynamic values that have not been
explicitly declared within the getTs
or useTs
instances.
// ❌ This won't work
const CHUNK_ID = 'common'
const ts = getTs({ chunkId: CHUNK_ID })
// ❌ This won't work
const tsOptions = { chunkId: 'common' }
const ts = useTs(tsOptions)
// ✅ This works
const ts = getTs({ chunkId: 'common' })
We acknowledge the limitations of this behavior, and we are actively working on enhancing this solution for future releases.