question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Official vite support?

See original GitHub issue

I wonder if lingui could provide a official support of vite?

I have seen related topic https://github.com/lingui/js-lingui/issues/1016 and even https://github.com/skovhus/vite-lingui but I am facing an issue with vite/esbuild and lingui/babel-macros.

Uncaught Error: Module "path" has been externalized for browser compatibility and cannot be accessed in client code.
    get @lingui_macro.js:143
    pathJoinPosix2 @lingui_macro.js:153239
    node_modules 

At the end vite/esbuild/rollup work in ESM mode and will convert the macro into ESM renaming the import file and so not detected as a macro anymore.

I have found out that we can tell vite to exclude lingui macro from CommonJs to ESM process with the following:

optimizeDeps: {
  exclude: ['@lingui/macro']
},
build: {
  commonjsOptions: {
    exclude: [/@lingui\/macro/]
  }
},

// Error: Uncaught SyntaxError: import not found: Trans

I did not found a working solution in the other topic yet and I would appreciate some help here and even if possible an official support of vite 🙂

In addition:

vite.config.js
import * as path from 'path';
import react from '@vitejs/plugin-react';
import { defineConfig } from 'vite';
import linguiLoader from './linguiVitePlugin';

// https://vitejs.dev/config/
export default defineConfig({
  define: {
    'process.env': process.env
  },
  server: {
    port: 3005,
  },
  preview: {
    port: 3006,
  },
  plugins: [
    react({
      babel: {
        configFile: true
      }
    }),
    linguiLoader({
      configPath: require.resolve('../../lingui.config.js')
    }),
  ],
  optimizeDeps: {
    exclude: ['@lingui/macro']
  },
  build: {
    commonjsOptions: {
      exclude: [/@lingui\/macro/]
    }
  },
  resolve: {
    alias: {
      '#app': path.resolve(__dirname, './src'),
    },
  },
});
linguiVitePlugin.js
const path = require('path')
const R = require('ramda')
const { getConfig } = require('@lingui/conf')
const { createCompiledCatalog, getCatalogs, getCatalogForFile } = require('@lingui/cli/api')

/**
 * Custom Vite Lingui loader plugin
 * Based on simple Vite svg plugin: https://github.com/jpkleemans/vite-svg-loader/blob/main/index.js
 * And webpack lingui loader: https://github.com/lingui/js-lingui/blob/main/packages/loader/src/webpackLoader.ts
 * @param options { configPath: string } need to specify the lingui config file
 */
module.exports = function linguiLoader (options) {
  let viteConfig = {}
  const poRegex = /\.po$/

  return {
    name: 'lingui-loader',
    enforce: 'pre',

    configResolved (config) {
      viteConfig = config
    },

    async load (id) {
      const isRootRef = viteConfig.command === 'build' && !id.startsWith(viteConfig.root)

      if (!id.match(poRegex) || isRootRef) {
        return
      }

      const config = getConfig({
        configPath: options.configPath,
        cwd: path.dirname(id),
      })

      const catalogRelativePath = path.relative(config.rootDir, id)

      const { locale, catalog } = getCatalogForFile(
        catalogRelativePath,
        getCatalogs(config)
      )
      const catalogs = catalog.readAll()
      const messages = R.mapObjIndexed(
        (_, key) =>
          catalog.getTranslation(catalogs, locale, key, {
            fallbackLocales: config.fallbackLocales,
            sourceLocale: config.sourceLocale,
          }),
        catalogs[locale]
      )

      // In production we don't want untranslated strings. It's better to use message
      // keys as a last resort.
      // In development, however, we want to catch missing strings with `missing` parameter
      // of I18nProvider (React) or setupI18n (core) and therefore we need to get
      // empty translations if missing.
      const strict = process.env.NODE_ENV !== 'production'
      return createCompiledCatalog(locale, messages, {
        strict,
        namespace: config.compileNamespace,
        pseudoLocale: config.pseudoLocale,
      })
    }
  }
}

module.exports.default = module.exports

Issue Analytics

  • State:closed
  • Created a year ago
  • Reactions:2
  • Comments:12 (6 by maintainers)

github_iconTop GitHub Comments

4reactions
skovhuscommented, Jun 23, 2022

@semoal awesome! I completely overlooked the option of not using vite-plugin-babel-macros. With your suggestion we now go from a production build taking 80s to 60s.

I’ll just updated the example repository. 👏

1reaction
a1oohacommented, Jul 14, 2022

I wrote a plugin for vite and more, which can compiles messages on the fly! It contains a demo for vite integration in the playground catalogs, Hope this helps.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Getting Started - Vite
Overview # · A dev server that provides rich feature enhancements over native ES modules, for example extremely fast Hot Module Replacement (HMR)....
Read more >
Vite | Next Generation Frontend Tooling
Hot Module Replacement (HMR) that stays fast regardless of app size. 🛠️. Rich Features. Out-of-the-box support for TypeScript, JSX, CSS and ...
Read more >
Vite 3.0 is out!
Maintainers from most of these projects got involved in improving the Vite core itself, working closely with the Vite team and other contributors....
Read more >
Features | Vite
Rewrite the imports to valid URLs like /node_modules/.vite/deps/my-dep.js?v=f3sf2ebd so that the browser can import them properly. Dependencies are Strongly ...
Read more >
Server-Side Rendering - Vite
SSR specifically refers to front-end frameworks (for example React, Preact, Vue, and Svelte) that support running the same application in Node.js, pre-rendering ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found