DEV Community

HarmonyOS
HarmonyOS

Posted on

Error occurred while compiling and building the library module: "Property 'xxxxx' of exported class expression may not be private or protected"

Read the original article:Error occurred while compiling and building the library module: "Property 'xxxxx' of exported class expression may not be private or protected"

Problem Description

When compiling and building the library module (Build -> Make Module 'library'), the following error message appears:

Property 'xxx' of exported class expression may not be private or protected.
Enter fullscreen mode Exit fullscreen mode

Background Knowledge

ArkTS provides private, protected, and public access modifiers. By default, properties use the public access modifier. Selecting the appropriate access modifier enhances code security and readability. Note: If a class contains private properties, it cannot be initialized via object literals. Set properties to public when literal creation or direct access is required. Refer to the ArkTS Programming Specification for details.

Troubleshooting Process

According to the error message, the exported class expression uses private or protected access modifiers to define properties, which may be accessible outside the class.

Analysis Conclusion

Exported modules may contain private or protected members. Outside the class, only public members can be directly accessed; private and protected members should not be used externally.

Solution

There are two ways to modify:

  1. Change the private or protected modifiers to public.
  2. Use the singleton pattern to globally utilize the instance exported from ClientTest. Refer to the following example code:
// src/main/ets/ClientTest.ets
class ClientTest {
  private name: string = ''
  private static instance: ClientTest | null = null

  private constructor() {
  }

  private testFun(): string {
    return ''
  }

  public static getInstance() {
    if (!ClientTest.instance) {
      ClientTest.instance = new ClientTest()
    }
    return ClientTest.instance
  }

  public setValue(c: string) {
    this.name = c
  }

  public getValue() {
    return this.name
  }
}

let a: ClientTest = ClientTest.getInstance()

export default a

// src/main/ets/RemoteApi.ets
import ClientTest from './ClientTest'

export class RemoteApi {
  // client  = ClientTest
  a = ClientTest.setValue('xxxx')
  client = ClientTest
}
Enter fullscreen mode Exit fullscreen mode

Written by Fatih Turan Gundogdu

Top comments (0)