Skip to content

Commit c31016c

Browse files
committed
Simplify injecting FTL code
1 parent df999f5 commit c31016c

File tree

1 file changed

+7
-8
lines changed

1 file changed

+7
-8
lines changed

src/plugins/ftl/inject.ts

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,10 @@ import MagicString from 'magic-string'
55

66
type InjectFtlFn = (template: TemplateStringsArray, locale?: string, source?: string) => MagicString
77

8+
function normalize(str: string) {
9+
return str.replace(/\r\n/g, '\n').trim()
10+
}
11+
812
export function getInjectFtl(options: SFCPluginOptions): InjectFtlFn {
913
return (template, locale, source) => {
1014
if (source == null) {
@@ -15,21 +19,16 @@ export function getInjectFtl(options: SFCPluginOptions): InjectFtlFn {
1519
if (source == null)
1620
throw new Error('Missing source')
1721

18-
let magic = new MagicString(source)
22+
const magic = new MagicString(source)
1923
const importString = options.parseFtl === true ? '' : '\nimport { FluentResource } from \'@fluent/bundle\'\n'
2024
const localeString = locale == null ? '' : locale
2125

2226
if (options.parseFtl === true) {
23-
const resource = new FluentResource(source)
27+
const resource = new FluentResource(normalize(source))
2428
magic.overwrite(0, source.length, JSON.stringify(resource))
2529
}
2630
else {
27-
// Escape string
28-
magic.replace(/"/g, '\\"')
29-
magic.replace(/\n/g, '\\n')
30-
magic = magic.snip(1, -1)
31-
magic.prepend('new FluentResource("')
32-
magic.append('")')
31+
magic.overwrite(0, source.length, `new FluentResource(${JSON.stringify(normalize(source))})`)
3332
}
3433

3534
magic.prepend(importString + template[0] + localeString + template[1])

0 commit comments

Comments
 (0)