Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: import messages with 2 fewer imports #1003

Merged
merged 1 commit into from
Dec 8, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions src/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import * as util from 'node:util';
import { fileURLToPath } from 'node:url';
import { AnyJson, asString, ensureJsonMap, ensureString, isJsonMap, isObject } from '@salesforce/ts-types';
import { ensureArray, NamedError, upperFirst } from '@salesforce/kit';
import { SfError } from './sfError';
Expand Down Expand Up @@ -172,6 +173,9 @@ const jsAndJsonLoader: FileParser = (filePath: string, fileContents: string): St
* // Create loader functions for all files in the messages directory
* Messages.importMessagesDirectory(__dirname);
*
* // or, for ESM code
* Messages.importMessagesDirectoryFromMetaUrl(import.meta.url)
*
* // Now you can use the messages from anywhere in your code or file.
* // If using importMessageDirectory, the bundle name is the file name.
* const messages: Messages = Messages.loadMessages(packageName, bundleName);
Expand Down Expand Up @@ -300,6 +304,22 @@ export class Messages<T extends string> {
}
}

/**
* Support ESM plugins who can't use __dirname
*
* @param metaUrl pass in `import.meta.url`
* @param truncateToProjectPath Will look for the messages directory in the project root (where the package.json file is located).
* i.e., the module is typescript and the messages folder is in the top level of the module directory.
* @param packageName The npm package name. Figured out from the root directory's package.json.
*/
public static importMessagesDirectoryFromMetaUrl(
metaUrl: string,
truncateToProjectPath = true,
packageName?: string
): void {
return Messages.importMessagesDirectory(path.dirname(fileURLToPath(metaUrl)), truncateToProjectPath, packageName);
}

/**
* Import all json and js files in a messages directory. Use the file name as the bundle key when
* {@link Messages.loadMessages} is called. By default, we're assuming the moduleDirectoryPart is a
Expand Down
Loading