Skip to content

Commit 747a5ea

Browse files
committed
Add option autoResolveKey
1 parent bc8afc1 commit 747a5ea

File tree

1 file changed

+29
-2
lines changed

1 file changed

+29
-2
lines changed

src/index.js

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
const nodePath = require('path');
2+
13
const FUNCTION_NAME = 'createDict';
24

35
const isDefineTranslationsFunction = (path, state) => {
@@ -15,7 +17,7 @@ const isDefineTranslationsFunction = (path, state) => {
1517
const getKey = path => path.node.name;
1618
const getValue = path => path.evaluate().value;
1719

18-
export default function () {
20+
export default function(babel) {
1921
return {
2022
pre(file) {
2123
file.set('translations', new Map());
@@ -35,12 +37,37 @@ export default function () {
3537
return;
3638
}
3739

40+
if (state.opts.autoResolveKey && path.node.arguments.length === 1) {
41+
if (!state.file.opts.filename) {
42+
throw new Error(
43+
'Filename not found by babel-plugin-intlized-components.',
44+
);
45+
}
46+
47+
const key = nodePath
48+
.relative(process.env.NODE_PATH, state.file.opts.filename)
49+
.replace(/\\/g, '/')
50+
.replace(/\//g, '.')
51+
.split('.')
52+
.slice(0, -1)
53+
.join('.');
54+
55+
path.replaceWith(
56+
babel.types.callExpression(path.node.callee, [
57+
babel.types.stringLiteral(key),
58+
path.node.arguments[0],
59+
]),
60+
);
61+
62+
path.stop();
63+
}
64+
3865
// parse translations
3966
const scope = path.get('arguments')[0];
4067
const definitions = path.get('arguments')[1];
4168

4269
// temporarily store translations
43-
definitions.get('properties').forEach((definition) => {
70+
definitions.get('properties').forEach(definition => {
4471
const translations = state.file.get('translations');
4572
const id = `${getValue(scope)}.${getKey(definition.get('key'))}`;
4673
const defaultMessage = getValue(definition.get('value'));

0 commit comments

Comments
 (0)