Coder Social home page Coder Social logo

lingui / swc-plugin Goto Github PK

View Code? Open in Web Editor NEW
59.0 59.0 8.0 412 KB

A SWC Plugin For LinguiJS

Home Page: https://www.npmjs.com/package/@lingui/swc-plugin

License: MIT License

Rust 100.00%
hacktoberfest i18n icu internationalization lingui messageformat swc swc-plugin

swc-plugin's People

Contributors

andrii-bodnar avatar bravo-kernel avatar martin005 avatar stovmascript avatar taozhou-glean avatar thekip avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

swc-plugin's Issues

A build error with Next.js

The recent release (v0.2.1) comes with the error:

note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace thread '<unnamed>' panicked at 'failed to invoke plugin: failed to invoke plugin

Caused by:
    0: failed to invoke `.../node_modules/@lingui/swc-plugin/target/wasm32-wasi/release/lingui_macro_plugin.wasm` as js transform plugin at /.../node_modules/@lingui/swc-plugin/target/wasm32-wasi/release/lingui_macro_plugin.wasm
    1: RuntimeError: out of bounds memory access
       at rkyv::impls::alloc::boxed::<impl rkyv::Deserialize<alloc::boxed::Box<T>,D>

Javascript heap out of memory

Thank you for this great work.

I have a javascript heap out of memory error when I try to run the extract command using your plugin. Here is the complete stacktrace

[biwano@localhost app]$ npx lingui extract

<--- Last few GCs --->

[181958:0x558f89923640]    67708 ms: Scavenge (reduce) 2042.5 (2081.9) -> 2042.0 (2082.2) MB, 8.5 / 0.0 ms  (average mu = 0.298, current mu = 0.315) allocation failure 
[181958:0x558f89923640]    67727 ms: Scavenge (reduce) 2042.8 (2082.2) -> 2042.2 (2082.2) MB, 11.5 / 0.0 ms  (average mu = 0.298, current mu = 0.315) allocation failure 
[181958:0x558f89923640]    67745 ms: Scavenge (reduce) 2043.4 (2082.5) -> 2042.8 (2082.8) MB, 7.6 / 0.0 ms  (average mu = 0.298, current mu = 0.315) allocation failure 


<--- JS stacktrace --->

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory
 1: 0x558f859ead94 node::Abort() [/usr/bin/node]
 2: 0x558f858a30b6 node::OnFatalError(char const*, char const*) [/usr/bin/node]
 3: 0x558f85bd7b5a v8::Utils::ReportOOMFailure(v8::internal::Isolate*, char const*, bool) [/usr/bin/node]
 4: 0x558f85bd7de6 v8::internal::V8::FatalProcessOutOfMemory(v8::internal::Isolate*, char const*, bool) [/usr/bin/node]
 5: 0x558f85d77eb9  [/usr/bin/node]
 6: 0x558f85d77ffc  [/usr/bin/node]
 7: 0x558f85d90535 v8::internal::Heap::PerformGarbageCollection(v8::internal::GarbageCollector, v8::GCCallbackFlags) [/usr/bin/node]
 8: 0x558f85d90df4 v8::internal::Heap::CollectGarbage(v8::internal::AllocationSpace, v8::internal::GarbageCollectionReason, v8::GCCallbackFlags) [/usr/bin/node]
 9: 0x558f85d93e34 v8::internal::Heap::AllocateRawWithLightRetrySlowPath(int, v8::internal::AllocationType, v8::internal::AllocationOrigin, v8::internal::AllocationAlignment) [/usr/bin/node]
10: 0x558f85d93ec9 v8::internal::Heap::AllocateRawWithRetryOrFailSlowPath(int, v8::internal::AllocationType, v8::internal::AllocationOrigin, v8::internal::AllocationAlignment) [/usr/bin/node]
11: 0x558f85d5de3f v8::internal::Factory::NewFillerObject(int, bool, v8::internal::AllocationType, v8::internal::AllocationOrigin) [/usr/bin/node]
12: 0x558f8609f200 v8::internal::Runtime_AllocateInYoungGeneration(int, unsigned long*, v8::internal::Isolate*) [/usr/bin/node]
13: 0x558f86475959  [/usr/bin/node]

Steps to reproduce:

git clone https://github.com/KlimaDAO/klimadao --branch 922_swc_plugin_for_lingui --depth 1
cd klimadao
npm install
npm run build-lib
cd app
npx lingui extract

I will try to dig deeper but I do not have knowledge of the swc architecture.

4.0.0-next.2 Could not resolve dependency

It fails to install the next version 4.0.0-next.2

I guess it can be fixed by setting peer dependency to >= 4.0.0-next < 5.

"peerDependencies": {
  "@lingui/macro": ">= 4.0.0-next < 5"
}

image

next version 13.4.9

Hi, can you please update readme why stable version 13.4.9 is not supported, or is it?

swc-plugin inserts imports before `"use client"`

The "use client" directive must be placed before other expressions.

ref: https://beta.nextjs.org/docs/rendering/server-and-client-components#convention

Minimal reproducible example

input.js

'use client'
import {t} from '@lingui/macro'
import foo from 'bar'
t`Text`

package.json

{
  "devDependencies": {
    "@lingui/swc-plugin": "0.2.0",
    "@swc/cli": "0.1.62",
    "@swc/core": "1.3.36"
  }
}

Actual

import { i18n } from "@lingui/core";
"use client";
import foo from "bar";
i18n._("Text");

Expected

"use client";
import { i18n } from "@lingui/core";
import foo from "bar";
i18n._("Text");

Macros are not processed inside .js/.mjs files.

It seems like the non-react macros (React isn't allowed in .js/.mjs anyways) like "t" are not processed inside .js or .mjs files. They are processed only in .ts, .tsx, and .jsx files.

The babel macros plugin does process the macro even in .js and .mjs files. Not sure if this is an SWC limitation.

// somefile.js
import { t } from '@lingui/macro';
const text = t`hello`;
[plugin:vite:import-analysis] The macro you imported from "@lingui/macro" is being executed outside the context of compilation. 
This indicates that you don't have the "babel-plugin-macros" or "@lingui/swc-plugin" configured correctly. Please see the documentation for how to configure Vite with Lingui correctly: https://lingui.dev/tutorials/setup-vite

I am on SWC core 1.3.56.
Vite 5.0.3.

Doesn't work with nextjs@12 compiler

next.config.js

  experimental: {
    swcPlugins: [
      ['@lingui/swc-plugin', {}],
    ],
  },

Receive error when build:

thread 'thread '<unnamed>' panicked at 'called `Result::unwrap()` on an `Err` value: LayoutError', /home/runner/.cargo/registry/src/github.com-1ecc6299db9ec823/rkyv-0.7.37/src/impls/core/mod.rs:265:67
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
<unnamed>' panicked at 'called `Result::unwrap()` on an `Err` value: LayoutError', /home/runner/.cargo/registry/src/github.com-1ecc6299db9ec823/rkyv-0.7.37/src/impls/core/mod.rs:265:67
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
thread 'thread '<unnamed><unnamed>thread '' panicked at '' panicked at 'failed to invoke plugin: failed to invoke plugin on 'Some("/Users/tim/projects/timescenery/node_modules/next/dist/client/router.js")'

Caused by:
    0: failed to invoke `/Users/tim/projects/timescenery/node_modules/@lingui/swc-plugin/target/wasm32-wasi/release/lingui_macro_plugin.wasm` as js transform plugin at /Users/tim/projects/timescenery/node_modules/@lingui/swc-plugin/target/wasm32-wasi/release/lingui_macro_plugin.wasm
    1: RuntimeError: out of bounds memory access
    2: heap_get_oob', <unnamed>/Users/runner/.cargo/registry/src/github.com-1ecc6299db9ec823/swc-0.226.26/src/plugin.rs' panicked at ':failed to invoke plugin: failed to invoke plugin on 'Some("/Users/tim/projects/timescenery/node_modules/next/dist/client/dev/amp-dev.js")'

Caused by:
    0: failed to invoke `/Users/tim/projects/timescenery/node_modules/@lingui/swc-plugin/target/wasm32-wasi/release/lingui_macro_plugin.wasm` as js transform plugin at /Users/tim/projects/timescenery/node_modules/@lingui/swc-plugin/target/wasm32-wasi/release/lingui_macro_plugin.wasm
    1: RuntimeError: unreachable
    2: unreachable', 216/Users/runner/.cargo/registry/src/github.com-1ecc6299db9ec823/swc-0.226.26/src/plugin.rs:failed to invoke plugin: failed to invoke plugin on 'Some("/Users/tim/projects/timescenery/node_modules/next/dist/client/next-dev.js")'

Caused by:
    0: failed to invoke `/Users/tim/projects/timescenery/node_modules/@lingui/swc-plugin/target/wasm32-wasi/release/lingui_macro_plugin.wasm` as js transform plugin at /Users/tim/projects/timescenery/node_modules/@lingui/swc-plugin/target/wasm32-wasi/release/lingui_macro_plugin.wasm
    1: RuntimeError: unreachable
    2: unreachable14', /Users/runner/.cargo/registry/src/github.com-1ecc6299db9ec823/swc-0.226.26/src/plugin.rs::216216::1414

note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

thread 'thread '<unnamed><unnamed>' panicked at '' panicked at 'failed to invoke plugin: failed to invoke plugin on 'Some("/Users/tim/projects/timescenery/projects/client-react/pages/_app.page.tsx")'

Next.js v12.3.1
Plugin: 0.1.0

Issue with variable naming convention for Lingui strings

Issue: Error: failed to process called Result::unwrap() on an Err value: DummyBytePos

Description:
When using Lingui strings with the "t" method, an error occurs when the variable names for these strings start with a capital letter and are placed outside of any code block, such as the file body scope. This error message is displayed:

Error: failed to process called `Result::unwrap()` on an `Err` value: DummyBytePos

Here is an example of the code structure that causes the error:

import { t } from "@lingui/macro";

const MSG = t`message`;

And examples where the code works without any issues:

import { t } from "@lingui/macro";

{
  const MSG = t`message`;
}

const text = t`text`;

const getMSG = () => { 
  const MY_MSG = t`message`;
  return MY_MSG;
}

Dependencies:

"@lingui/core": "^4.0.0",
"@lingui/macro": "^4.0.0",
"@lingui/react": "^4.0.0",
"@lingui/swc-plugin": "^4.0.0",

Update:
I'm also using NextJs 13.3.2

How bad .clone() is and how to avoid it?

I often face a situation when i have only a reference to some part of AST and trying to create a new nodes which wants to own the value, the most common example:

    fn fold_expr(&mut self, expr: Expr) -> Expr {
        if let Expr::TaggedTpl(tagged_tpl /* &TaggedTpl */) = &expr {
            create_new_node(tagged_tpl /* TaggedTpl */) // Type mismatch &TaggedTpl -> TaggedTpl
        }

        expr.fold_children_with(self)
    }

So i've forced to clone the tagged_tpl to be able to get non-referenced value. How bad is that? And how to avoid this?
How to do pattern matching while still keeping ownership of value.

If I write it like that, I get another error:

    fn fold_expr(&mut self, expr: Expr) -> Expr {
        if let Expr::TaggedTpl(tagged_tpl /* TaggedTpl */) = expr {
            create_new_node(tagged_tpl /* TaggedTpl */) 
        }

        expr.fold_children_with(self) // use of partially moved value, value was moved in pattern matching expr
    }

Error on build: Filesystem cache is not enabled, cannot read plugin from phsyical path

Hi there,

I'm currently facing an error while trying to build my NextJS project with the latest version of dependencies. The error message is as follows:

./node_modules/next/dist/pages/_document.js
Error: Filesystem cache is not enabled, cannot read plugin from physical path

./node_modules/next/dist/pages/_error.js
Error: Filesystem cache is not enabled, cannot read plugin from physical path

./src/pages/[locale]/index.tsx
Error: Filesystem cache is not enabled, cannot read plugin from physical path

./src/pages/_app.tsx
Error: Filesystem cache is not enabled, cannot read plugin from physical path

./src/pages/index.tsx
Error: Filesystem cache is not enabled, cannot read plugin from physical path

Here are the relevant dependencies:

"dependencies": {
  "@lingui/core": "^4.2.0",
  "@lingui/react": "^4.2.0",
  "next": "13.4.4",
  "react": "18.2.0",
  "react-dom": "18.2.0"
},
"devDependencies": {
  "@lingui/cli": "^4.2.0",
  "@lingui/loader": "^4.2.0",
  "@lingui/macro": "^4.2.0",
  "@lingui/swc-plugin": "^4.0.1",
  "@types/node": "20.1.5",
  "@types/react": "18.2.6",
  "eslint": "8.35.0",
  "eslint-config-next": "12.3.4",
  "typescript": "5.0.4"
}

To reproduce the issue, you can refer to this example repository.

Please note that the repository has two commits. The first commit represents a working setup with outdated dependencies, while the last commit is the one causing the error.

Any assistance or guidance in resolving this issue would be greatly appreciated.

Thank you!

Extract translation still requires @babel/preset-react

Great plugin, one thing which doesn't work for me is

NODE_ENV=development lingui extract --clean

This is the error
Add @babel/preset-react (https://github.com/babel/babel/tree/main/packages/babel-preset-react) to the 'presets' section of your Babel config to enable transformation.
If you want to leave it as-is, add @babel/plugin-syntax-jsx (https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-jsx) to the 'plugins' section to enable parsing.

Do you know any workarounds for this one?

Doesn't work in NextJS 13.2.4

Adding this swc plugin causes the next dev server to fail to start.

// next.config.js
  experimental: {
    swcPlugins: [['@lingui/swc-plugin', {}]],
  },

It is worked fine before upgrading Next.js

Capitalization issues

`
import { t } from '@lingui/macro'

const Name = tedsonlin
console.log(Name)
`

@swc/core: 1.3.58
@lingui/swc-plugin: 4.0.2

it does not work, it seems that there is an error in the data

thread '' panicked at 'called Result::unwrap() on an Err value: DummyBytePos', /Users/runner/.cargo/registry/src/index.crates.io-6f17d22bba15001f/swc_ecma_transforms_react-0.172.25/src/refresh/mod.rs:159:74


but, if i write like next line

`
import { t } from '@lingui/macro'

const name = tedsonlin
console.log(Name)
`

it works! so i think it maybe treat capitalization as react, do you have any resolution to solve it? plz help me

Adding @lingui/swc-plugin to react while using @vitejs/plugin-react-swc crashes the application.

I am currently facing an issue here.

Here's my vitejs configuration

import { lingui } from '@lingui/vite-plugin';
import react from '@vitejs/plugin-react-swc';
import { visualizer } from 'rollup-plugin-visualizer';
import { defineConfig, type PluginOption } from 'vite';
import tsconfigPaths from 'vite-tsconfig-paths';
import { configDefaults } from 'vitest/config';

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    react({ plugins: [['@lingui/swc-plugin', {}]] }),
    lingui(),
    visualizer({
      brotliSize: true,
      emitFile: true,
      filename: 'bundle-size.html',
      gzipSize: true,
    }) as PluginOption,
    tsconfigPaths(),
  ],
  test: {
    ...configDefaults,
    environment: 'jsdom',
    exclude: ['**/node_modules/**', '**/dist/**'],
    include: ['**/*.test.{ts,tsx}'],
    name: 'jsdom',
    setupFiles: ['../setupTests.ts'],
  },
});

When adding plugins: [['@lingui/swc-plugin', {}]] in my configuration, it crashes the whole application.

It is randomly crashing at a component with unexpected token error because it's not compiling properly after adding this plugin.

Currently using these versions:
@lingui/swc-plugin 4.0.2

defineMessage missing comments

import { msg } from '@lingui/macro'
const testMsg = msg`Hello world`

// โ†“ โ†“ โ†“ โ†“ โ†“ โ†“

const testMsg = {
    id: "1nGWAC",
    message: "Hello world"
};

The conversion is correct, but the comment is missing

const testMsg = /*i18n*/ {
    id: "1nGWAC",
    message: "Hello world"
};

In this way, extract cli can extract

Next 13.4.3 onwards issue with swcPlugins

Hello,

as of Next 13.4.3 I'm having issues with this plugin being used in my project. I troubleshooted on a blank Next project and my current work project, with both projects having the same dependency setup.

The second I add this to my next.config:
experimental: { swcPlugins: [ [ "@lingui/swc-plugin", {} ] ] }
My project dies with the following error messages from that issue: vercel/next.js#36078 (comment)

Could this, be in any way, related to the swc Plugin? I've trialed another swc plugin and it didn't cause the issue.

Running the 4.0.0 Plugin due to the swc core issue.

Incompatible with next > 13.4.8

Starting from next 13.4.8 (also tested 13.4.9, and 13.4.10), I can no longer build my application when @lingui/swc-plugin is enabled. 13.4.7 works fine.
I get the following error:

thread '<unnamed>' panicked at 'invalid utf8 character detected: FromUtf8Error { bytes: [LONG ARRAY WITH NUMBERS HERE], error: Utf8Error { valid_up_to: 324, error_len: Some(1) } }', /Users/runner/.cargo/registry/src/index.crates.io-6f17d22bba15001f/swc-0.264.12/src/lib.rs:555:40

MORE OF THE ABOVE MESSAGES...

./src/app/[locale]/chats/live/@menu/List.tsx
Module parse failed: Unexpected token (29:8)
File was processed with these loaders:
 * ./node_modules/next/dist/build/webpack/loaders/next-flight-client-module-loader.js
 * ./node_modules/next/dist/build/webpack/loaders/next-swc-loader.js
You may need an additional loader to handle the result of these loaders.
|             "chats",
|             this?.
>         ],
|         queryFn: ()=>new API().getList({
|                 resource: "chats",

MOEV OF THE ABOVE MESSAGES...

Seems to have something to do with conditional chaining.

Jest tests fail on v0.2.1

It seems that #22 introduced something which is throwing off our unit tests. I ran them with RUST_BACKTRACE=full if it's any help. Wondering where to look ๐Ÿค” Here's the output of one failed test:

Errors thrown in src/helpers/prettyBytes.test.js
    โ— Test suite failed to run
  
      failed to process failed to invoke plugin: failed to invoke plugin on 'Some("/home/runner/work/monitora-frontend/monitora-frontend/src/helpers/prettyBytes.test.js")'
  
      Caused by:
          0: failed to invoke `/home/runner/work/monitora-frontend/monitora-frontend/node_modules/@lingui/swc-plugin/target/wasm32-wasi/release/lingui_macro_plugin.wasm` as js transform plugin at /home/runner/work/monitora-frontend/monitora-frontend/node_modules/@lingui/swc-plugin/target/wasm32-wasi/release/lingui_macro_plugin.wasm
          1: RuntimeError: out of bounds memory access
                 at rkyv::impls::alloc::boxed::<impl rkyv::Deserialize<alloc::boxed::Box<T>,D> for rkyv::boxed::ArchivedBox<<T as rkyv::ArchiveUnsized>::Archived>>::deserialize::h78606889e733645c (<module>[503]:0x6c5ad)
                 at rkyv::impls::alloc::vec::<impl rkyv::Deserialize<alloc::vec::Vec<T>,D> for rkyv::vec::ArchivedVec<<T as rkyv::Archive>::Archived>>::deserialize::hbc27da83d658c665 (<module>[70]:0xb7a0)
                 at __transform_plugin_process_impl (<module>[593]:0x7b87f)
                 at __transform_plugin_process_impl.command_export (<module>[1587]:0xfc109)
          2: heap_get_oob
  
      Stack backtrace:
         0: <unknown>
         1: <unknown>
         2: <unknown>
         3: <unknown>
         4: <unknown>
         5: <unknown>
         6: <unknown>
         7: <unknown>
         8: <unknown>
         9: <unknown>
        10: <unknown>
        11: <unknown>
        12: _ZN6v8impl12_GLOBAL__N_123FunctionCallbackWrapper6InvokeERKN2v820FunctionCallbackInfoINS2_5ValueEEE
        13: _ZN2v88internal12_GLOBAL__N_119HandleApiCallHelperILb0EEENS0_11MaybeHandleINS0_6ObjectEEEPNS0_7IsolateENS0_6HandleINS0_10HeapObjectEEESA_NS8_INS0_20FunctionTemplateInfoEEENS8_IS4_EENS0_16BuiltinArgumentsE
        14: _ZN2v88internal21Builtin_HandleApiCallEiPmPNS0_7IsolateE
        15: Builtins_CEntry_Return1_DontSaveFPRegs_ArgvOnStack_BuiltinExit
  
      Stack backtrace:
         0: <unknown>
         1: <unknown>
         2: <unknown>
         3: <unknown>
         4: _ZN6v8impl12_GLOBAL__N_123FunctionCallbackWrapper6InvokeERKN2v820FunctionCallbackInfoINS2_5ValueEEE
         5: _ZN2v88internal12_GLOBAL__N_119HandleApiCallHelperILb0EEENS0_11MaybeHandleINS0_6ObjectEEEPNS0_7IsolateENS0_6HandleINS0_10HeapObjectEEESA_NS8_INS0_20FunctionTemplateInfoEEENS8_IS4_EENS0_16BuiltinArgumentsE
         6: _ZN2v88internal21Builtin_HandleApiCallEiPmPNS0_7IsolateE
         7: Builtins_CEntry_Return1_DontSaveFPRegs_ArgvOnStack_BuiltinExit
  
        at rkyv::impls::alloc::boxed::<impl rkyv::Deserialize<alloc::boxed::Box<T>,D> for rkyv::boxed::ArchivedBox<<T as rkyv::ArchiveUnsized>::Archived>>::deserialize::h78606889e733645c (<module>[503]:0x6c5ad)
        at rkyv::impls::alloc::vec::<impl rkyv::Deserialize<alloc::vec::Vec<T>,D> for rkyv::vec::ArchivedVec<<T as rkyv::Archive>::Archived>>::deserialize::hbc27da83d658c665 (<module>[70]:0xb7a0)
                   at __transform_plugin_process_impl (<module>[593]:0x7b87f)
                   at __transform_plugin_process_impl.command_export (<module>[1[587](https://github.com/monitora-media/monitora-frontend/actions/runs/4253106361/jobs/7397538783#step:6:589)]:0xfc109)
            2: heap_get_oob
        Stack backtrace:
           0: <unknown>
           1: <unknown>
           2: <unknown>
           3: <unknown>
           4: <unknown>
           5: <unknown>
           6: <unknown>
           7: <unknown>
           8: <unknown>
           9: <unknown>
          10: <unknown>
          11: <unknown>
          12: _ZN6v8impl12_GLOBAL__N_123FunctionCallbackWrapper6InvokeERKN2v820FunctionCallbackInfoINS2_5ValueEEE
          13: _ZN2v88internal12_GLOBAL__N_119HandleApiCallHelperILb0EEENS0_11MaybeHandleINS0_6ObjectEEEPNS0_7IsolateENS0_6HandleINS0_10HeapObjectEEESA_NS8_INS0_20FunctionTemplateInfoEEENS8_IS4_EENS0_16BuiltinArgumentsE
          14: _ZN2v88internal21Builtin_HandleApiCallEiPmPNS0_7IsolateE
          15: Builtins_CEntry_Return1_DontSaveFPRegs_ArgvOnStack_BuiltinExit
        Stack backtrace:
           0: <unknown>
           1: <unknown>
           2: <unknown>
           3: <unknown>
           4: _ZN6v8impl12_GLOBAL__N_123FunctionCallbackWrapper6InvokeERKN2v820FunctionCallbackInfoINS2_5ValueEEE
           5: _ZN2v88internal12_GLOBAL__N_119HandleApiCallHelperILb0EEENS0_11MaybeHandleINS0_6ObjectEEEPNS0_7IsolateENS0_6HandleINS0_10HeapObjectEEESA_NS8_INS0_20FunctionTemplateInfoEEENS8_IS4_EENS0_16BuiltinArgumentsE
           6: _ZN2v88internal21Builtin_HandleApiCallEiPmPNS0_7IsolateE
           7: Builtins_CEntry_Return1_DontSaveFPRegs_ArgvOnStack_BuiltinExit
        at Object.transformSync (node_modules/src/build/swc/index.ts:357:25)
        at Object.transformSync (node_modules/src/build/swc/index.ts:476:19)
        at Object.process (node_modules/src/build/swc/jest-transformer.ts:74:67)
        at ScriptTransformer.transformSource (node_modules/@jest/transform/build/ScriptTransformer.js:542:31)
        at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:671:40)

nextjs-swc is unusable

First render by SSR:

/es
image

/
image

AboutText componnent do not translate completely.


After change path by CSR: / => /es

image

Developers component translation is still English translation. after CSR /es => / path it use Spanish translation. It looks like CSR always use previous translation. It is so ridiculous...

'Trans is not defined' when doing a build for production

Hi all, currently I'm trying this plugin together with vite + react + ts. When I'm starting my app as a dev server via vite dev everything works fine. But when I'm doing a production build via vite build and start the the production build locally then I'm getting a ReferenceError: Trans is not defined on the console:

image
image

It seems like that the transformation does not happen and Trans from @lingui/react is missing when doing a build for production.

Does anyone have any idea if I am doing something wrong?

My current setup is:

.linguirc

{
   "locales": ["en", "de", "lb", "fr", "pt", "it", "nl", "ru"],
   "sourceLocale": "en",
   "compileNamespace": "ts",
   "catalogs": [{
      "path": "src/locales/{locale}/messages",
      "include": ["src"],
      "exclude": ["**/node_modules/**"]
   }],
   "format": "po",
   "extractBabelOptions": {
      "presets": [
         "@babel/preset-typescript",
         [
           "@babel/preset-react",
           {
             "runtime": "automatic",
             "importSource": "react"
           }
         ]
       ]
    }
}

package.json

"dependencies": {
    // ...
    "@lingui/macro": "3.17.1",
    "@lingui/react": "3.17.1",
    "react": "18.2.0",
    "react-dom": "18.2.0",
  },
  "devDependencies": {
    //...
    "@babel/core": "7.20.12",
    "@babel/eslint-parser": "7.19.1",
    "@babel/plugin-syntax-flow": "7.18.6",
    "@babel/plugin-syntax-jsx": "7.18.6",
    "@babel/plugin-transform-react-jsx": "7.20.13",
    "@babel/preset-react": "7.18.6",
    "@babel/preset-typescript": "7.18.6",
    "@lingui/cli": "3.17.1",
    "@lingui/swc-plugin": "0.2.0",
    "@lingui/vite-plugin": "3.17.1",
    "@vitejs/plugin-react-swc": "3.1.0",
    "babel-eslint": "10.1.0",
    "babel-plugin-macros": "3.1.0",
    "typescript": "4.9.5",
    "vite": "4.1.2"
  }

vite.config.ts

import lingui from "@lingui/vite-plugin";
import react from "@vitejs/plugin-react-swc";
import { defineConfig } from "vite";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    lingui(),
    react({
      plugins: [
        [
          "@lingui/swc-plugin",
          {
            runtimeModules: {
              i18n: ["@lingui/core", "i18n"],
              trans: ["@lingui/react", "Trans"],
            },
          },
        ],
      ],
    }),
  ],
  server: {
    port: 3000,
  },
  resolve: {
    alias: {
      src: "/src",
    },
  },
});

When parsing jsx, seems that it doesn't check that at least <Select /> tag is imported from lingui

I've just tested the plugin on a project I own. First of all, thank you @thekip for your work, so easy to setup and works โšก.

The only issue I've encountered from now is this one:

  1. I have a Select component in the project
  2. Seems that the plugin threat it as a lingui <Select /> tag
  3. So it results to the following error message: Message cannot be parsed due to syntax errors: {0, select,}{1}

In order to make it work and have a temporary fix, I've aliased our component (import { Select as Selector }ย from ...) so the plugin ignores it.

Duplicate import aliases bug

import { t as $t, t } from '@lingui/macro'

t`Hello`

$t`Hello`

Only the last t variable will be registered in imports_id_map

Maybe need to add a secondary data structure importsBindingMap?

// export name -> local name
importsIdMap: Map<string, string>
// local name -> export name
importsIdMapInverted: Map<string, string>


// local name -> ast node
importsBindingMap: Map<string, Set<Identifier>>

If swc has babel's scope.getBinding, it can maintain the importsBindingMap during the registration phase.

Please extend swc's capabilities๏ฝž

<Trans /> without an explicit `id` matching the translation files renders a random string on next build only

On next dev, My translations are working accordingly, with or without an id passed to them

import { Trans } from "@lingui/macro";
...
return ( <Trans>Home</Trans>) // successfully display `Home` on the page

However, when doing a next build following by a next start, the page renders a random string.
If do set an id : <Trans id="home-id">Home</Trans> then the page renders home-id instead of Home

All my Trans that have an id mapping to an explicit translation in my translation files render fine btw.

Is it anything wrong in my configuration that prevents next build to correctly map a Trans to their children if no id exists/correspond to a translation (while next dev works fine)?

// .linguirc

{
  "format": "minimal",
  "catalogs": [
    {
      "path": "<rootDir>/catalogs/{locale}/messages",
      "include": [
        "<rootDir>/src/"
      ],
      "exclude": [
        "/node_modules/",
        "<rootDir>/src/types/"
      ]
    }
  ],
  "sourceLocale": "en-GB",
  "fallbackLocales": {
    "default": "en-GB"
  },
  "locales": [
    "en-GB",
    "de-DE",
    "fr-FR",
    "es-ES"
  ],
  "rootDir": ".",
  "extractBabelOptions": {
    "presets": [
      "@babel/preset-typescript",
      "@babel/preset-react"
    ]
  }
}

// next.config.js config

const config = {
  publicRuntimeConfig: {
    __APP_CONFIG__: nodeConfig,
  },
  
  // to account for https://github.com/lingui/js-lingui/issues/1048
  rules: [
    {
      resourceQuery: /raw-lingui/,
      type: "javascript/auto",
    },
  ],
  experimental: {
    swcPlugins: [["@lingui/swc-plugin", {}]],
  },
  compiler: {
    emotion: true,
  },
};

package.json


    "@lingui/react": "^3.14.0",
    "@lingui/cli": "^3.10.2",
    "@lingui/loader": "^3.10.2",
    "@lingui/macro": "^3.14.0",
    "@lingui/swc-plugin": "^4.0.4",
    "@swc/core": "^1.3.99",
    "next": "^13.5.6",

SWC 4.0.1 plugin panics on latest @swc/core version 1.3.60

Describe the bug
If I have @swc/core 1.3.60 I get a panic and server fails to start. Forcing 1.3.49 fixes the issue and it works. 1.3.56 seems to be the highest version that still works.

@lingui/swc-plugin 4.0.1 does not work with any version (I tried @swc/core 1.3.49 up to 1.3.60).
@lingui/swc-plugin 4.0.0 works with up to @swc/core 1.3.56.

To Reproduce
Install @swc/core 1.3.60 and run project with @lingui/swc-plugin.

Adding this to package.json and reinstalling fixes the issue, suggesting it is just the new swc version causing the problem.

  "resolutions": {
    "@swc/core": "1.3.49"
  },

Expected behavior
It should not panic and crash.

Additional context
Add any other context about the problem here.

  • jsLingui version 4.1.2
  • Babel version 7.21.8
  • Macro support:
  • [X ] I'm using SWC with @lingui/swc-plugin
  • I'm using Babel with babel-macro-plugin
  • I'm not using macro
  • Your Babel config (e.g. .babelrc) or framework you use (Create React App, NextJs, Vite)
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react-swc";
import linaria from "@linaria/vite";
import { lingui } from "@lingui/vite-plugin";

export default defineConfig({
  plugins: [
    react({
      plugins: [
        [
          "@lingui/swc-plugin", {}
        ],
      ],
    }),
    linaria(),
    lingui(),
  ],
});
thread '<unnamed>' panicked at 'called `Result::unwrap()` on an `Err` value: LayoutError', /home/runner/.cargo/registry/src/index.crates.io-6f17d22bba15001f/rkyv-0.7.41/src/impls/core/mod.rs:266:67
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
thread '<unnamed>' panicked at 'failed to invoke plugin: failed to invoke plugin on 'Some("/Users/[redacted]/src/entry/server.tsx")'

Caused by:
    0: failed to invoke `/Users/[redacted]/node_modules/@lingui/swc-plugin/target/wasm32-wasi/release/lingui_macro_plugin.wasm` as js transform plugin at /Users/[redacted]/node_modules/@lingui/swc-plugin/target/wasm32-wasi/release/lingui_macro_plugin.wasm
    1: RuntimeError: unreachable', /Users/runner/.cargo/registry/src/index.crates.io-6f17d22bba15001f/swc-0.261.25/src/plugin.rs:152:14
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
node:internal/process/promises:288
            triggerUncaughtException(err, true /* fromPromise */);
            ^

[Error: failed to handle: failed to invoke plugin: failed to invoke plugin on 'Some("/Users/[redacted]/src/entry/server.tsx")'

Caused by:
    0: failed to invoke `/Users/[redacted]/node_modules/@lingui/swc-plugin/target/wasm32-wasi/release/lingui_macro_plugin.wasm` as js transform plugin at /Users/[redacted]/node_modules/@lingui/swc-plugin/target/wasm32-wasi/release/lingui_macro_plugin.wasm
    1: RuntimeError: unreachable] {
  code: 'GenericFailure',
  plugin: 'vite:react-swc',

Macro imports get stripped in rollup and never placed back

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?

if !has_trans_import && self.ctx.should_add_trans_import {

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.

Fatal Error with @swc/core > 1.3.105

Last version of @swc/core that works with this plugin is 1.3.105.

Upgrading to @swc/core:1.4 or @swc/core:1.3.x fill fail.
OS Windows.

Caused by:
    0: failed to invoke `C:\workspace\node_modules\@lingui\swc-plugin\target\wasm32-wasi\release\lingui_macro_plugin.wasm` as js transform plugin at 
C:\workspace\node_modules\@lingui\swc-plugin\target\wasm32-wasi\release\lingui_macro_plugin.wasm
    1: RuntimeError: unreachable
           at __rust_start_panic (<module>[2736]:0x11be35)
           at rust_panic (<module>[2728]:0x11bb9e)
           at std::panicking::rust_panic_with_hook::hccaf2b7e6df76f84 (<module>[2727]:0x11bb65)
           at std::panicking::begin_panic_handler::{{closure}}::hf6623888c16dc6bb (<module>[2715]:0x11ac13)
           at std::sys_common::backtrace::__rust_end_short_backtrace::h585f9f94f404c402 (<module>[2714]:0x11ab3d)
           at rust_begin_unwind (<module>[2722]:0x11b1d1)
           at core::panicking::panic_fmt::h1e0ee2f017a8252e (<module>[2867]:0x129b29)
           at core::result::unwrap_failed::h10ae8691526cb788 (<module>[2904]:0x12ff7a)
           at rkyv::impls::alloc::vec::<impl rkyv::Deserialize<alloc::vec::Vec<T>,D> for rkyv::vec::ArchivedVec<<T as rkyv::Archive>::Archived>>::deserialize::ha7c5bcea2c12eee9 (<module>[412]:0x60f48)
           at rkyv::impls::core::<impl rkyv::DeserializeUnsized<T,D> for <T as rkyv::Archive>::Archived>::deserialize_unsized::hc9024ee97bd35ba4 (<module>[76]:0x12565)
           at swc_ecma_ast::expr::_::<impl rkyv::Deserialize<swc_ecma_ast::expr::MemberExpr,__D> for <swc_ecma_ast::expr::MemberExpr as rkyv::Archive>::Archived>::deserialize::h1ad15d83dd09b194 (<module>[105]:0x284df)
           at rkyv::impls::core::<impl rkyv::DeserializeUnsized<T,D> for <T as rkyv::Archive>::Archived>::deserialize_unsized::hc9024ee97bd35ba4 (<module>[76]:0x138a7)
           at rkyv::impls::core::<impl rkyv::DeserializeUnsized<T,D> for <T as rkyv::Archive>::Archived>::deserialize_unsized::hc9024ee97bd35ba4 (<module>[76]:0x124fd)
           at swc_ecma_ast::stmt::_::<impl rkyv::Deserialize<swc_ecma_ast::stmt::Stmt,__D> for <swc_ecma_ast::stmt::Stmt as rkyv::Archive>::Archived>::deserialize::hf29be54d952adb60 (<module>[110]:0x29fb2)
           at rkyv::impls::alloc::vec::<impl rkyv::Deserialize<alloc::vec::Vec<T>,D> for rkyv::vec::ArchivedVec<<T as rkyv::Archive>::Archived>>::deserialize::h54a0a2a0cf609a47 (<module>[20]:0x322e)
           at swc_common::plugin::serialized::_::<impl rkyv::Deserialize<swc_common::plugin::serialized::VersionedSerializable<T>,__D> for <swc_common::plugin::serialized::VersionedSerializable<T> as rkyv::Archive>::Archived>::deserialize::h4f433e64d5224fb8 (<module>[19]:0x2842)
           at __transform_plugin_process_impl (<module>[473]:0x6b175)
           at __transform_plugin_process_impl.command_export (<module>[3025]:0x137278)
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
{
  // package.json
  "dependencies": {
    "@lingui/detect-locale": "^4.7.0",
    "@lingui/react": "^4.7.0",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-router-dom": "^6.22.0"
  },
  "devDependencies": {
    "@lingui/cli": "^4.7.0",
    "@lingui/macro": "^4.7.0",
    "@lingui/swc-plugin": "^4.0.4",
    "@lingui/vite-plugin": "^4.7.0",
    "@types/react": "^18.2.53",
    "@types/react-dom": "^18.2.18",
    "@typescript-eslint/eslint-plugin": "^6.20.0",
    "@typescript-eslint/parser": "^6.20.0",
    "@vitejs/plugin-react-swc": "^3.6.0",
    "typescript": "^5.3.3",
    "vite": "^5.0.12",
    "vite-plugin-svgr": "^4.2.0",
    "vite-tsconfig-paths": "^4.3.1",
    "vitest": "^1.2.2"
  },
  "overrides": {
    "vite": "$vite"
  }
}

as a workaround @swc/core version must be fixed as follows:

{
  // package.json
  "overrides": {
    "@swc/core": "1.3.105"
  }
}

Add Code Coverage report

  • add CI step that will run tests and generate a code coverage report compatible with the Codecov (it may require some additional configuration. Example: codecov/example-rust)
  • add CI step that will publish the report to Codecov (ask @andrii-bodnar to create a repository secret with the token)
  • add badge to the Readme

Whitespaces & Trimming

Original Babel Macro use following code:

// replace whitespace before/after newline with single space
const keepSpaceRe = /\s*(?:\r\n|\r|\n)+\s*/g
// remove whitespace before/after tag or expression
const stripAroundTagsRe = /(?:([>}])(?:\r\n|\r|\n)+\s*|(?:\r\n|\r|\n)+\s*(?=[<{]))/g

function normalizeWhitespace(text) {
  return (
    text
      .replace(stripAroundTagsRe, "$1")
      .replace(keepSpaceRe, " ")
      // keep escaped newlines
      .replace(/\\n/g, "\n")
      .replace(/\\s/g, " ")
      // we remove trailing whitespace inside Plural
      .replace(/(\s+})/gm, "}")
      .trim()
  )
}

And not only. Also few pieces are spread among other code. There are few problems with this:

I could not directly port this into Rust because Rust's Regexp engine doesn't support lookahead/lookbehind.

So I need to write a code which should mimic this behavior in rust code. To do so i should understand all edge cases and generic spec behind this part of code.

This is so crucial because if even one additional space character in the processed after macro code it will cause translation mismatch (no translation for string would be found)

The only one source of truth for now is babel/macro fixtures, but i'm afraid they might not cover all cases which this regexp include.

So if someone has an idea and would like to help me with that i would appreciate this.

How to use it with macro support?

I would like to use this as a drop in replacement for babel, but it seems it's not possible if using macro? Mainly these code break

import { t, Trans } from '@lingui/macro'

<Trans>...some text...</Trans>

t`...some text...`

Without babel I always got this error

./node_modules/@lingui/conf/index.js:22:0
Module not found: Can't resolve 'fs'

Import trace for requested module:
./node_modules/@lingui/macro/index.js

And this error

TypeError: _lingui_macro__WEBPACK_IMPORTED_MODULE_3__.t is not a function

support @swc/[email protected]

hi
1 hope to support @swc/[email protected]

2 maybe add dependencies in swc-plugin/package.json to lock version of swc ,like this

  "dependencies": {
    "@swc/core": "^1.3.107"
  }

rather than write this in package.json

  "resolutions": {
    "@swc/core": "1.3.105"
  },
image

Trans macro inside ConditionalExpressions are not processed

Related PR in upstream repo: lingui/js-lingui#1436

To Reproduce

import { Trans } from '@lingui/macro'

export default function Component(props) {
  return <Trans>Hello, {props.world ? <Trans>world</Trans> : <Trans>guys</Trans>}</Trans>
}

Expected behaviour

import { Trans } from '@lingui/react'

export default function Component(props) {
  return (
    <Trans
      id='Hello, {0}'
      values={{
        0: props.world ? <Trans id='world' /> : <Trans id='guys' />
      }}
    />
  )
}

Actual behaviour

import { Trans } from '@lingui/react'

export default function Component(props) {
  return (
    <Trans
      id='Hello, {0}'
      values={{
        0: props.world ? <Trans>world</Trans> : <Trans>guys</Trans>
      }}
    />
  )
}

Nextjs 13.x not working with typewind plugin using SWC

I am also trying to use Typewind with tailwind config. but it is not working. It seems we can't use any custom plugin with nextjs 13.x.

Also If i am trying to use babel. then its working fine but not able to use most of the latest support from nextjs 13 like fonts giving error. it is asking SWC environment.

Nextjs team please help fix this or give me a workaround to move further. it is extremely required for us.

I also raise some query on Typewind but it is related to Nextjs 13.x

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.