lingui / swc-plugin

A SWC Plugin For LinguiJS
https://www.npmjs.com/package/@lingui/swc-plugin
MIT License
63 stars 10 forks source link

Macro imports get stripped in rollup and never placed back #74

Closed daphnesmit closed 1 year ago

daphnesmit commented 1 year ago

I am using rollup to build a react package in ts with lingui macros.

When building with latest version of swc-plugin it is removing the Trans imports from the file but never putting them pack from @lingui/react.

looking at this file that should happen? https://github.com/lingui/swc-plugin/blob/3a4b3b2f430052c8a5df7aebe2fa4effeec0010d/src/lib.rs#L176

Resulting in that when I import the package its saying "Trans is undefined"

Here are my files:

Build result example using Trans:

import { __makeTemplateObject, __assign, __spreadArray, __awaiter, __generator } from '../../node_modules/tslib/tslib.es6.js';
import { jsx, jsxs } from 'react/jsx-runtime';
import { useState, useMemo, useEffect, useCallback } from 'react';
import styled from 'styled-components';

....other component imports

var StyledFooter = styled(ButtonGroup)(templateObject_1 || (templateObject_1 = __makeTemplateObject([
    "\n  margin-left: auto;\n"
], [
    "\n  margin-left: auto;\n"
])));
var AddToReadingListDrawerContent = function(_a) {
    var isLoading = _a.isLoading, hasError = _a.hasError, onReset = _a.onReset, children = _a.children;
    if (isLoading) {
        return jsx(DrawerLoader, {
            loadingText: jsx(Trans, {
                children: "Leeslijsten opslaan..."
            }),
            testId: "addToReadingListDrawerLoading"
        });
    }
    if (hasError) {
        return jsx(DrawerError, {
            buttonText: jsx(Trans, {
                children: "Opnieuw proberen"
            }),
            description: jsx(Trans, {
                children: "Probeer het nog later nog eens"
            }),
            testId: "addToReadingListDrawerError",
            title: jsx(Trans, {
                children: "Helaas is het opslaan van sommige leeslijsten mislukt"
            }),
            onReset: onReset
        });
    }

build result using tString:

import { __makeTemplateObject } from '../../node_modules/tslib/tslib.es6.js';
import { jsx } from 'react/jsx-runtime';
import { i18n } from '@lingui/core';
import { useLingui } from '@lingui/react';
import { InputField } from '../FormFields/InputField.js';

var CreateReadingListForm = function() {
    useLingui();
    return jsx(InputField, {
        autoComplete: "off",
        label: i18n._(templateObject_1 || (templateObject_1 = __makeTemplateObject([
            "Naam"
        ], [
            "Naam"
        ]))),
        name: "name",
        placeholder: i18n._(templateObject_2 || (templateObject_2 = __makeTemplateObject([
            "Naam van de leeslijst"
        ], [
            "Naam van de leeslijst"
        ]))),
        testId: "createReadingListFormName"
    });
};

Rollup config:

import commonjs from '@rollup/plugin-commonjs';
import json from '@rollup/plugin-json';
import resolve from '@rollup/plugin-node-resolve';
import typescriptPlugin from '@rollup/plugin-typescript';
import url from '@rollup/plugin-url';
import externals from 'rollup-plugin-node-externals';

import swc from '@rollup/plugin-swc';
import graphql from '@rollup/plugin-graphql';
import { readFile } from 'fs/promises';

const pkg = JSON.parse(await readFile(new URL('./package.json', import.meta.url)));

function dirname(file) {
  const [root, folder] = file.split('/');
  return `${root}/${folder}`;
}

function createDefaultRollupConfig(pkg) {
  return {
    input: pkg.source,
    output: [
      {
        dir: dirname(pkg.main),
        format: 'cjs',
        exports: 'named',
        preserveModules: true,
        preserveModulesRoot: 'src',
        sourcemap: true,
        interop: 'auto',
      },
      {
        dir: dirname(pkg.module),
        exports: 'named',
        preserveModules: true,
        preserveModulesRoot: 'src',
        sourcemap: true,
        interop: 'auto',
      },
    ],
    plugins: [
      externals(),
      url(),
      resolve(),
      json(),
      typescriptPlugin({
        exclude: ['**/*.test.tsx', '**/*.stories.tsx'],
      }),
      commonjs(),
    ],
  };
}

const defaultRollupConfig = createDefaultRollupConfig(pkg);

export default {
  ...defaultRollupConfig,

  plugins: [
    ...defaultRollupConfig.plugins,

    swc({
      swc: {
        jsc: {
          experimental:{
            plugins: [
              [
                '@lingui/swc-plugin',
                {},
                },
              ],
            ],
          }
        },
      },
    })
  ],
};

I am not exactly sure if this is a swc-plugin issue or something else conflicting.

timofei-iatsenko commented 1 year ago

I am not exactly sure if this is a swc-plugin issue or something else conflicting.

Rather something else in your Rollup Config....

Looking at the resulting code it seems the macro was not expanded by plugin, and imports were deleted by something else. Typescript for example could delete imports because it encounters that actual import {Trans} from "@lingui/macro" pointing to declaration only.

Looking at your config i don't understand why you need both typescript and swc. Use just SWC without a typescript.

daphnesmit commented 1 year ago

Ah yeah. That was it! sorry!