A bit late for the party but this how I solved this issue:
Assumption, you have created a Custom LWC component, in this example you'll see different URL's for Standard and Community pages.
Let's start by adding a property line named environment to file to the custom component js-metadata, save & deploy it:
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>52.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__RecordPage</target>
<target>lightning__AppPage</target>
<target>lightning__HomePage</target>
<target>lightningCommunity__Page</target>
<target>lightningCommunity__Default</target>
</targets>
<targetConfigs>
<targetConfig targets="lightningCommunity__Default">
<property name="recordId" type="String" label="Record ID" description="Should be set to {!recordId}"/>
<property name="environment" type="String" label="Environment" description="Variable to define if the page is Community" />
</targetConfig>
</targetConfigs>
</LightningComponentBundle>
Second, add the variable to your custom component JS file:
@api environment;
Third, right after the variable environment, will add the code to create different URLs
baseUrl = window.location.origin + '/';
connectedCallback(){
if(this.environment === 'Community'){
this.baseUrl = window.location.origin + '/' + 'opportunitylineitem' + '/';
}
}
Both variables will be in the same file so, save & deploy it.
Fourth, we need to set the variable under the Community Page:
Navigate to Setup > Feature Settings > All Sites > Select your
website by clicking on Builder next to its name
Builder will open, under Home click on it and find your custom
component

Select your Custom LWC and fill out Environment variable: Community. After that change no need to save, just Publish your Portal.
