opencc-js

repository·main·Indexed 43 days ago

https://github.com/nk2028/opencc-js

A pure JavaScript implementation of Open Chinese Convert (OpenCC) for browsers and Node.js. It provides high-fidelity Simplified and Traditional Chinese character conversion without native binaries. Version 1.4.2 includes features such as HTML content conversion via HTMLConverter(), custom dictionary support through CustomConverter(), and a ConverterFactory for combining standard locales with custom words.

Tokens
8.1K
Snippets
31
Records
41
Agent score
55%

What's inside opencc-js

  1. Compare opencc-js with other OpenCC npm packages

    main

    There are three primary OpenCC-related npm packages. Choosing the right one depends on your runtime environment (Browser vs. Node.js), implementation requirements (Pure JS vs. Native), and whether you need specific segmentation algorithms like Jieba.

    Comparison Summary

    Featureopencc-jsopenccopencc-wasm
    Browser Support✅❌✅
    Node.js Support✅✅✅
    ImplementationPure JavaScriptNative C++ bindingWebAssembly
    Native Binary Required❌✅❌
    Dictionary SourceBundled at build timeLoaded at runtimeLoaded at runtime
    Alignment with Official OpenCCApproximate✅✅
    mmseg Segmentation✅✅✅
    Jieba Segmentation Support❌✅✅
  2. API differences between opencc-js and opencc

    main

    The API patterns for opencc-js and opencc are incompatible.

    opencc-js Pattern: Uses factory functions to return a plain converter function. Key entry points include:

    • OpenCC.Converter({ from, to })
    • ConverterFactory
    • Locale

    opencc Pattern: Uses a class-based approach. You instantiate it with new OpenCC(config, options) and call methods like convertSync, convert, or convertPromise.

    Note on Configuration: If you are looking for OpenCC.fromConfig() (used in the native opencc package to build a converter from an inline configuration object), you should use the ConverterFactory or CustomConverter API in opencc-js to achieve the same custom-conversion use case.

  3. Understand API differences between opencc-js and opencc

    main

    The API patterns for opencc-js and the native opencc package are fundamentally different and are not interchangeable.

    opencc-js API Pattern

    opencc-js uses a factory pattern. It provides factory functions like OpenCC.Converter({ from, to }), ConverterFactory, and Locale to return a standard conversion function. It does not follow the native opencc class-based API.

    opencc (Native) API Pattern

    The native opencc package uses a class-based approach (new OpenCC(config, options)) and provides specific methods such as convertSync, convert, and convertPromise. It also includes OpenCC.fromConfig() for building converters from inline configuration objects, a feature not present in opencc-js.

    Customization

    While the native package uses fromConfig(), opencc-js handles custom conversion requirements through its own ConverterFactory and CustomConverter APIs.

  4. Choose the right OpenCC npm package

    main

    There are three main OpenCC-related npm packages, each suited for different environments and requirements:

    1. opencc-js: A pure JavaScript implementation for Browsers and Node.js. It bundles dictionary data at build time, meaning it requires no native binaries and does not download dictionary files at runtime. It aligns closely with official OpenCC logic (including mmseg style segmentation) but does not support extended segmentation like Jieba. Use this for lightweight, zero-dependency, or browser-based projects.

    2. opencc: A Node.js native binding for the official OpenCC C++ project. It requires native or prebuilt binaries and is the most faithful to the official engine. It supports extended segmentation algorithms like Jieba. Use this for high-performance Node.js server-side applications where native dependencies are acceptable.

    3. opencc-wasm: A WebAssembly implementation for Browsers and Node.js. It aligns its configuration and logic with the official opencc package and supports Jieba segmentation via the official OpenCC runtime. Use this if you need browser support with Jieba segmentation capabilities.

    Comparison Summary

    Featureopencc-jsopenccopencc-wasm
    Browser Support✅❌✅
    Node.js Support✅✅✅
    ImplementationPure JavaScriptNative C++ bindingWebAssembly
    Native Binary Required❌✅❌
    Dictionary SourceBundled at build timeLoaded at runtimeLoaded at runtime
    Official AlignmentApproximate✅✅
    mmseg Segmentation✅✅✅
    Jieba Segmentation❌✅✅
  5. Optimize bundle size with opencc-js/core and opencc-js/preset

    main

    To reduce bundle size (Tree Shaking), avoid importing the full opencc-js package. Instead, import from /core and /preset separately.

    Recommended Pattern:

    import * as OpenCC from 'opencc-js/core'; // core logic
    import * as Locale from 'opencc-js/preset'; // dictionary data
    
    const converter = OpenCC.ConverterFactory(Locale.from.hk, Locale.to.cn);
    console.log(converter('漢語'));

    Optimization Tips:

    1. Use ConverterFactory instead of Converter.
    2. Prefer regional output dictionaries (like tw or hk) over the intermediate OpenCC standard t unless specifically required.
    import * as OpenCC from 'opencc-js/core';
    import * as Locale from 'opencc-js/preset';
    
    const converter = OpenCC.ConverterFactory(Locale.from.hk, Locale.to.cn);
    console.log(converter('漢語'));
  6. Optimize bundle size with Tree Shaking

    main

    To reduce bundle size, use ES Modules and import only the core logic and the specific presets you need. Use ConverterFactory instead of Converter for better optimization.

    import * as OpenCC from 'opencc-js/core'; // Core logic
    import * as Locale from 'opencc-js/preset'; // Dictionaries
    
    const converter = OpenCC.ConverterFactory(Locale.from.hk, Locale.to.cn);
    console.log(converter('漢語'));
    import * as OpenCC from 'opencc-js/core';
    import * as Locale from 'opencc-js/preset';
    
    const converter = OpenCC.ConverterFactory(Locale.from.hk, Locale.to.cn);
    console.log(converter('漢語'));
  7. Use opencc-js in the Browser

    main

    You can load opencc-js directly in the browser using ES modules via a self-hosted file or a CDN. For older script tag usage, use the UMD build.

    Self-hosted ES module:

    <script type="module">
      import OpenCC from './dist/esm/full.js';
      const converter = OpenCC.Converter({ from: 'cn', to: 'tw' });
      console.log(converter('汉语')); // 漢語
    </script>

    CDN ES module (Recommended):

    <script type="module">
      import OpenCC from 'https://cdn.jsdelivr.net/npm/opencc-js@1.4.2/dist/esm/full.js';
      const converter = OpenCC.Converter({ from: 'cn', to: 'tw' });
      console.log(converter('汉语')); // 漢語
    </script>

    UMD build (for standard <script> tags):

    <script src="https://cdn.jsdelivr.net/npm/opencc-js@1.4.2/dist/umd/full.js"></script>
    <script type="module">
      import OpenCC from 'https://cdn.jsdelivr.net/npm/opencc-js@1.4.2/dist/esm/full.js';
    
      const converter = OpenCC.Converter({ from: 'cn', to: 'tw' });
      console.log(converter('汉语')); // 漢語
    </script>
  8. Install opencc-js for Node.js or Bundlers

    main

    To use opencc-js in a Node.js environment or with a modern bundler (like Webpack, Vite, or Rollup), install it via npm.

    ES Modules:

    import OpenCC from 'opencc-js';

    CommonJS:

    const OpenCC = require('opencc-js');
    npm install opencc-js
  9. Understand conversion chain and dictionary priority

    main

    In opencc-js, conversion processes are defined by a chain of stages.

    • Stages: The outer array in a conversion configuration represents the sequence of stages in the conversion chain.
    • Dictionary Groups: The inner array represents a group of dictionaries used within a single stage.
    • Priority: Within a dictionary group, dictionaries listed earlier have higher priority. If multiple dictionaries in the same group contain overlapping entries, the earlier ones are applied first.
  10. Convert HTML content using HTMLConverter

    main

    The OpenCC.HTMLConverter() allows you to automatically convert text content within a DOM tree based on the lang attribute.

    Workflow:

    1. Define target elements using the lang='*' attribute (e.g., <span lang="zh-HK">).
    2. Initialize the handler with a converter, a root node, the initial language attribute, and the new language attribute.
    3. Call .convert() to perform the transformation or .restore() to revert.

    Example:

    <span lang="zh-HK">漢語</span>
    const converter = OpenCC.Converter({ from: 'hk', to: 'cn' });
    const rootNode = document.documentElement;
    
    // Converts all elements with lang='zh-HK' to lang='zh-CN' and translates their text
    const HTMLConvertHandler = OpenCC.HTMLConverter(converter, rootNode, 'zh-HK', 'zh-CN');
    
    HTMLConvertHandler.convert(); // Translates text to: 汉语
    HTMLConvertHandler.restore(); // Reverts text to: 漢語

    Note: The converter also processes placeholder and aria-label attributes. To prevent an element and its children from being converted, add the CSS class ignore-opencc.

    const converter = OpenCC.Converter({ from: 'hk', to: 'cn' });
    const rootNode = document.documentElement;
    const HTMLConvertHandler = OpenCC.HTMLConverter(converter, rootNode, 'zh-HK', 'zh-CN');
    HTMLConvertHandler.convert();
    HTMLConvertHandler.restore();