DEV Community

Cover image for how to use i18n in ant design pro project
antd-ts-admin
antd-ts-admin

Posted on

how to use i18n in ant design pro project

Image description

Image description

Image description

look at my code:

Image description

two way to use

  1. hook
import { useIntl } from '@umijs/max';
...

const TableList: React.FC = () => {
  const intl = useIntl();
...

  {
      title: intl.formatMessage({ id: 'country' }),
      width: 150,
      // filters: true,
      // onFilter: true,
      dataIndex: 'country',
      valueEnum: convertToTextObject(locationMapping),
    },
    {
      title: intl.formatMessage({ id: 'platform' }),
      // filters: true,
      // onFilter: true,
      width: 100,
      dataIndex: 'platform',
      valueEnum: convertToTextObject(platformNames),
    },
Enter fullscreen mode Exit fullscreen mode

intl.formatMessage({ id: 'platform' }) for translate.

  1. component
// import
import { FormattedMessage } from '@umijs/max';

const userColumns: ProColumns<API.ItemData>[] = [
  {
    title: <FormattedMessage id="email" defaultMessage="Email" />,
    dataIndex: 'email',
    copyable: true,
  },
  {
    title: <FormattedMessage id="name" defaultMessage="Name" />,
    dataIndex: 'name',
  },
  {
    title: <FormattedMessage id="role" defaultMessage="Role" />,
    dataIndex: 'role',
    valueEnum: {
      SUPER_ADMIN: { text: <FormattedMessage id="super_admin" defaultMessage="Super Admin" /> },
      CUSTOMER: { text: <FormattedMessage id="customer" defaultMessage="Customer" /> },
      ORDER_CLERK: { text: <FormattedMessage id="order_clerk" defaultMessage="Order Clerk" /> },
      ADMIN: { text: <FormattedMessage id="admin" defaultMessage="Admin" /> },
      FINANCIAL_STAFF: {
        text: <FormattedMessage id="financial_staff" defaultMessage="Financial Staff" />,
      },
    },
  },
];
Enter fullscreen mode Exit fullscreen mode

the example code: <FormattedMessage id="email" defaultMessage="Email" />

or like this:

// src/utils/constants.tsx

import { FormattedMessage } from '@umijs/max';

export const locationMapping = {
  'Vietnam Ho Chi Minh': (
    <FormattedMessage id="vietnam_ho_chi_minh" defaultMessage="越南胡志明 (VNH)" />
  ),
  'Vietnam Hanoi': <FormattedMessage id="vietnam_hanoi" defaultMessage="越南河内 (VN)" />,
  Thailand: <FormattedMessage id="thailand" defaultMessage="泰国 (TH)" />,
  Malaysia: <FormattedMessage id="malaysia" defaultMessage="马来西亚 (MY)" />,
  Philippines: <FormattedMessage id="philippines" defaultMessage="菲律宾 (PH)" />,
  Indonesia: <FormattedMessage id="indonesia" defaultMessage="印尼 (ID)" />,
};

export const platformNames = {
  Shopee: 'Shopee',
  Lazada: 'Lazada',
  TikTok: 'TikTok',
};

interface TextObject {
  [key: string]: { text: any };
}

export const convertToTextObject = (obj: Record<string, any>): TextObject => {
  const newObj: TextObject = {};
  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      newObj[key] = { text: obj[key] };
    }
  }
  return newObj;
};
Enter fullscreen mode Exit fullscreen mode

how to use locales file:

export default {
  country: 'Country',
  select_country: 'Please select a country',
  platform: 'Platform',
  select_platform: 'Please select a platform',
  user: 'User',
  quantity: 'Quantity',
  enter_quantity: 'Please enter the quantity',
  upload_file: 'Upload file',
  upload_time: 'Upload time',
  select_order_time: 'Please select the order time',
  order_time_selection: 'Order time selection',
  normal_order: 'Normal order',
  specific_time_order: 'Specific time order',
  order_time: 'Order time',
  order_time_notice:
    'Please upload 2 hours in advance if there is a time requirement. It takes time to connect with the buyer. Thank you for your understanding and cooperation.',
  review_type: 'Review Type',
  normal_review: 'Normal Review',
}
Enter fullscreen mode Exit fullscreen mode

I write two bash shell file to add some file and codes quickly.

  1. add_file_i18n.sh
#!/bin/bash

# Define directories and file names
dir="./src/locales"
filename=$1
module_name=$(basename $filename .ts)

# Traverse through directories and their subdirectories
for file in $(find "$dir" -mindepth 1 -maxdepth 1 -type f -name "*.ts")
do
  # Create new files and add content in each directory
  subdir="${dir}/$(basename $file .ts)"
  mkdir -p $subdir
  echo -e "export default {\n\n}" > "${subdir}/${filename}"

  # Generate import statements
  locale=$(basename $file .ts)
  import_statement="import $module_name from './${locale}/$module_name';"

  # Insert import statements into corresponding *.ts files
  sed -i '' -e "/import settings/a\\
$import_statement
" "$file"

  # Add ...$module_name under ...component,
  sed -i '' -e "/...component,/a\\
    ...$module_name,
" "$file"

  # Output import statements
  echo $import_statement
done
Enter fullscreen mode Exit fullscreen mode

This script automates the process of adding localization modules to a project by performing the following tasks:

It creates new TypeScript files in each language directory within the specified project directory.
It generates import statements for the newly created localization modules.
It inserts these import statements into existing TypeScript files.
It adds the imported modules under the appropriate section in the existing TypeScript files.

example: bash ~/add_file_i18n.sh app.ts

  1. create.sh
#!/bin/bash

# Accept command-line arguments
filename=$1
componentDefinition=$2

# Define the line to be inserted
lineToInsert="import { useIntl } from '@umijs/max';"

# Traverse through all specified files in the src/pages directory
find ./src/pages -name "$filename" | while read file
do
  # Insert the new line at the beginning of the file
  sed -i "" "1i\\
$lineToInsert
" "$file"
done

# Define the line to be inserted
lineToInsert="const intl = useIntl();"

# Traverse through all specified files in the src/pages directory
find ./src/pages -name "$filename" | while read file
do
  # Find the specified component definition line in the file and insert the new line after it
  sed -i "" "/$componentDefinition/a\\
$lineToInsert
" "$file"
done
Enter fullscreen mode Exit fullscreen mode

This script performs the following tasks:

It accepts two command-line arguments: filename and componentDefinition.
It inserts an import statement for the useIntl hook from the '@umijs/max' library at the beginning of each specified file in the 'src/pages' directory.
It inserts a line of code (const intl = useIntl();) after the specified component definition line in each specified file within the 'src/pages' directory.

example: bash ~/create.sh Create.tsx "const Create: React.FC"

Top comments (0)