[SalesForce] SFDX & How to handle namespace in lwc with a managed package

I'm developing some lightning-web-components for a managed package with namespace example7. For all my previous dev work on this managed package, I was using aura rather than lwc, and developing in a non-namespaced scratch org.

With LWC, now that we can import the apex methods into the js file, I'm unsure how to handle the namespace. The docs say:

import apexMethod from '@salesforce/apex/Namespace.Classname.apexMethod'

… and when deployed in the managed package that would be…

import apexMethod from '@salesforce/apex/example7.Classname.apexMethod'

So, my questions:

  1. do I hardcode the example7 namespace into the code of the js file?
  2. does that mean I need to be developing in a namespaced scratch org?
  3. do I similarly need to hardcode the namespace into the api-object-name in things like lightning-record-edit?

Best Answer

Thanks @Anshul Agrawal, you've confirmed what I figured out yesterday. For others facing the same issues, here's what I've discovered:

You don't need to include the package namespace in the @import for apexMethods or fieldnames. Within the javascript file, it appears to pick up on Apex's ability to adapt to the namespace.

However, if you want to use any of the lightning components like lightning-record-edit-form, when you put the api-object-name into the html tags, you DO need to add the namespace to both the object name, as well as any fields you specify in the markup. These components interact with the server without any explicit apex intervention, so you have to include the namespace.

Therefore, in answer to my own question #2, yes, I'm working in a scratch org with my package namespace. To accomplish that, first you have to link the packaging org that owns the namespace to your dev hub.

Then you have to specify the namespace in the scratch-org definition file in VS Code. You'll find that file in .sfdx/config/whatever.json. This is the definition file you'll specify as you create the scratch org. Looks like this...

{
"orgName": "your Company",
"edition": "Enterprise",
"namespace": "your_namespace",
"orgPreferences" : {
    "enabled": ["S1DesktopEnabled"],
    "disabled": ["S1EncryptedStoragePref2"]
}

}

Related Topic