Git Product home page Git Product logo

vite-plugin-cjs-interop's Introduction

vite-plugin-cjs-interop

Vite plugin to unwrap default imports from CJS dependencies during SSR.

Problem

In Node.js, when a CJS module that contains both a default export and named exports is imported from an ESM module, the default export has to be accessed via the default property of the imported module. Prior to version 5, Vite had some logic to handle this during development, but it didn't apply to SSR builds with external CJS dependencies. Since Vite 5, the problem happens in development as well. You don't get any indication that it won't work in production. TypeScript doesn't complain either.

Solution

This plugin will automatically unwrap the default export from CJS dependencies that you specify during SSR builds. In other words, the following code:

import foo, { named, named2 as renamed } from "foo";

will be transformed into:

const {
  default: foo = __cjsInterop1__,
  named,
  named2: renamed,
} = __cjsInterop1__?.default?.__esModule
  ? __cjsInterop1__.default
  : __cjsInterop1__;
import __cjsInterop1__ from "foo";

which takes care of unwrapping the default export and creating a synthetic default export if necessary.

The change for dynamic imports is more complicated, but allows the import() function to resolve to an object that not only resembles the standard ES6 namespace as expected, but also a CommonJS export:

const foo = await import("foo");

// ES6 namespace, with default export
foo.default.bar(); // Works

// CommonJS Module (some libraries expect this to work because webpack allows it)
foo.bar(); // Also works

Installation

npm install -D vite-plugin-cjs-interop

Usage

// vite.config.js
import { cjsInterop } from "vite-plugin-cjs-interop";

export default {
  plugins: [
    cjsInterop({
      // List of CJS dependencies that require interop
      dependencies: [
        "some-package",
        // Deep imports should be specified separately
        "some-package/deep/import",
        // But globs are supported
        "some-package/foo/*",
        // Even deep globs for scoped packages
        "@some-scope/**",
        // If you want to skip a specific package, you can use negative globs
        "!@donottransformme/**",
      ],
    }),
  ],
};

The matcher uses minimatch underneath, for more details on supported syntax.

License

MIT

vite-plugin-cjs-interop's People

Contributors

ael-imra avatar aheissenberger avatar cyco130 avatar dac09 avatar danielfalk avatar msaspence avatar renovate[bot] avatar tadeaspetak 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  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

vite-plugin-cjs-interop's Issues

@sentry/react does not appear to get fixed

My configuration:

cjsInterop({
  dependencies: ['@sentry/react'],
}),

and I am still getting error:

b8d6ae3d > SyntaxError: [vite] Named export 'withScope' not found. The requested module '@sentry/react' is a CommonJS module, which may not support all module.exports as named exports.
b8d6ae3d > CommonJS modules can always be imported via the default export, for example using:
b8d6ae3d >
b8d6ae3d > import pkg from '@sentry/react';
b8d6ae3d > const {captureException, captureMessage, close, setUser, showReportDialog, withScope} = pkg;
b8d6ae3d >
b8d6ae3d >     at analyzeImportedModDifference (file:///Users/gajus/Developer/contra/gaia/node_modules/.pnpm/[email protected]_@[email protected][email protected]/node_modules/vite/dist/node/chunks/dep-BzxBS-ea.js:54262:19)
b8d6ae3d >     at nodeImport (file:///Users/gajus/Developer/contra/gaia/node_modules/.pnpm/[email protected]_@[email protected][email protected]/node_modules/vite/dist/node/chunks/dep-BzxBS-ea.js:54213:9)
b8d6ae3d >     at ssrImport (file:///Users/gajus/Developer/contra/gaia/node_modules/.pnpm/[email protected]_@[email protected][email protected]/node_modules/vite/dist/node/chunks/dep-BzxBS-ea.js:54108:24)
b8d6ae3d >     at eval (/Users/gajus/Developer/contra/gaia/packages/sentry/src/react.ts:27:13)
b8d6ae3d >     at instantiateModule (file:///Users/gajus/Developer/contra/gaia/node_modules/.pnpm/[email protected]_@[email protected][email protected]/node_modules/vite/dist/node/chunks/dep-BzxBS-ea.js:54170:9)
b8d6ae3d > ┌────────────────────────────────────────────────────────────────────────────────────────────────────────┐
b8d6ae3d >  Error could be a CJS/ESM issue, consider using ssr.noExternal, see https://vike.dev/broken-npm-package │
b8d6ae3d > └────────────────────────────────────────────────────────────────────────────────────────────────────────┘

If it helps, @sentry/react is a dependency of a dependency in the same mono repo, as opposed to a direct dependency.

What debugging information can I provide?

I patched the plugin to produce some debugging information:

      walk(ast, {
        enter(node) {
          if (node.type === "ImportDeclaration") {
            console.log('>>', node.source.value);

            if (matchesDependencies(node.source.value)) {
              toBeFixed.push(node);

              console.log('>', toBeFixed);
            }
          } else if (node.type === "ImportExpression") {
            if (node.source.type === "Literal" && matchesDependencies(node.source.value)) {
              dynamicImportsToBeFixed.push(node);
            }
          }
        }
      });

so it does detect it:

e7686f01 > >> @sentry/react
e7686f01 > > [
e7686f01 >   Node {
e7686f01 >     type: 'ImportDeclaration',
e7686f01 >     start: 45,
e7686f01 >     end: 98,
e7686f01 >     loc: SourceLocation { start: [Position], end: [Position] },
e7686f01 >     specifiers: [ [Node], [Node] ],
e7686f01 >     source: Node {
e7686f01 >       type: 'Literal',
e7686f01 >       start: 82,
e7686f01 >       end: 97,
e7686f01 >       loc: [SourceLocation],
e7686f01 >       value: '@sentry/react',
e7686f01 >       raw: "'@sentry/react'"
e7686f01 >     }
e7686f01 >   }
e7686f01 > ]

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

github-actions
.github/workflows/ci.yml
  • actions/checkout v4
  • pnpm/action-setup v4.0.0
  • actions/setup-node v4
.github/workflows/publish.yml
  • actions/checkout v4
  • actions/setup-node v4
npm
package.json
  • husky ^9.1.4
  • lint-staged ^15.2.8
  • prettier ^3.3.3
  • typescript ^5.5.4
tests/bench/package.json
  • vite ^5.4.0
tests/cjs-test-package/package.json
vite-plugin-cjs-interop/package.json
  • acorn ^8.12.1
  • acorn-import-assertions ^1.9.0
  • estree-walker ^3.0.3
  • magic-string ^0.30.11
  • minimatch ^10.0.1
  • @cyco130/eslint-config ^3.9.4
  • @types/minimatch ^5.1.2
  • @types/node ^18.19.44
  • eslint ^8.57.0
  • publint ^0.2.9
  • tsup ^8.2.4
  • typescript ^5.5.4
  • vite ^5.4.0
  • vitest ^2.0.5

  • Check this box to trigger a request for Renovate to run again on this repository

acorn parser crashes on CSS files

When plugin is configured with client: true, apply: 'server' it will also receive CSS code which currently breaks the parsing process.

Error:

file:///waku-mantine/node_modules/.pnpm/[email protected]/node_modules/acorn/dist/acorn.mjs:3567
  var err = new SyntaxError(message);
            ^

SyntaxError: Unexpected token (1:0)
    at pp$4.raise (file:///waku-mantine/node_modules/.pnpm/[email protected]/node_modules/acorn/dist/acorn.mjs:3567:13)
    at pp$9.unexpected (file:///waku-mantine/node_modules/.pnpm/[email protected]/node_modules/acorn/dist/acorn.mjs:766:8)
    at pp$5.parseExprAtomDefault (file:///waku-mantine/node_modules/.pnpm/[email protected]/node_modules/acorn/dist/acorn.mjs:2930:8)
    at pp$5.parseExprAtom (file:///waku-mantine/node_modules/.pnpm/[email protected]/node_modules/acorn/dist/acorn.mjs:2925:17)
    at pp$5.parseExprSubscripts (file:///waku-mantine/node_modules/.pnpm/[email protected]/node_modules/acorn/dist/acorn.mjs:2709:19)
    at pp$5.parseMaybeUnary (file:///waku-mantine/node_modules/.pnpm/[email protected]/node_modules/acorn/dist/acorn.mjs:2675:17)
    at pp$5.parseExprOps (file:///waku-mantine/node_modules/.pnpm/[email protected]/node_modules/acorn/dist/acorn.mjs:2602:19)
    at pp$5.parseMaybeConditional (file:///waku-mantine/node_modules/.pnpm/[email protected]/node_modules/acorn/dist/acorn.mjs:2585:19)
    at pp$5.parseMaybeAssign (file:///waku-mantine/node_modules/.pnpm/[email protected]/node_modules/acorn/dist/acorn.mjs:2552:19)
    at pp$5.parseExpression (file:///waku-mantine/node_modules/.pnpm/[email protected]/node_modules/acorn/dist/acorn.mjs:2515:19) {
  pos: 0,
  loc: Position { line: 1, column: 0 },
  raisedAt: 1,
  plugin: 'cjs-interop',
  id: '\x00/appshell/mantine/date?html-proxy&direct&index=0.css',
  pluginCode: ':root{--mantine-font-family: Open Sans, sans-serif;--mantine-font-family-headings: Open Sans, sans-serif;--mantine-primary-color-filled: var(--mantine-color-orange-filled);--mantine-primary-color-filled-hover: var(--mantine-color-orange-filled-hover);--mantine-primary-color-light: var(--mantine-color-orange-light);--mantine-primary-color-light-hover: var(--mantine-color-orange-light-hover);--mantine-primary-color-light-color: var(--mantine-color-orange-light-color);--mantine-primary-color-0: var(--mantine-color-orange-0);--mantine-primary-color-1: var(--mantine-color-orange-1);--mantine-primary-color-2: var(--mantine-color-orange-2);--mantine-primary-color-3: var(--mantine-color-orange-3);--mantine-primary-color-4: var(--mantine-color-orange-4);--mantine-primary-color-5: var(--mantine-color-orange-5);--mantine-primary-color-6: var(--mantine-color-orange-6);--mantine-primary-color-7: var(--mantine-color-orange-7);--mantine-primary-color-8: var(--mantine-color-orange-8);--mantine-primary-color-9: var(--mantine-color-orange-9);--mantine-color-myColor-0: #fff4e2;--mantine-color-myColor-1: #ffe9cc;--mantine-color-myColor-2: #ffd09c;--mantine-color-myColor-3: #fdb766;--mantine-color-myColor-4: #fca13a;--mantine-color-myColor-5: #fb931d;--mantine-color-myColor-6: #fc8c0c;--mantine-color-myColor-7: #e17900;--mantine-color-myColor-8: #c86a00;--mantine-color-myColor-9: #ae5a00;}:root[data-mantine-color-scheme="dark"]{--mantine-color-anchor: var(--mantine-color-orange-4);--mantine-color-myColor-text: var(--mantine-color-myColor-4);--mantine-color-myColor-filled: var(--mantine-color-myColor-8);--mantine-color-myColor-filled-hover: var(--mantine-color-myColor-9);--mantine-color-myColor-light: rgba(252, 140, 12, 0.15);--mantine-color-myColor-light-hover: rgba(252, 140, 12, 0.2);--mantine-color-myColor-light-color: var(--mantine-color-myColor-3);--mantine-color-myColor-outline: var(--mantine-color-myColor-4);--mantine-color-myColor-outline-hover: rgba(252, 161, 58, 0.05);}:root[data-mantine-color-scheme="light"]{--mantine-color-anchor: var(--mantine-color-orange-6);--mantine-color-myColor-text: var(--mantine-color-myColor-filled);--mantine-color-myColor-filled: var(--mantine-color-myColor-6);--mantine-color-myColor-filled-hover: var(--mantine-color-myColor-7);--mantine-color-myColor-light: rgba(252, 140, 12, 0.1);--mantine-color-myColor-light-hover: rgba(252, 140, 12, 0.12);--mantine-color-myColor-light-color: var(--mantine-color-myColor-6);--mantine-color-myColor-outline: var(--mantine-color-myColor-6);--mantine-color-myColor-outline-hover: rgba(252, 140, 12, 0.05);}',
  frame: '1  |  :root{--mantine-font-family: Open Sans, sans-serif;--mantine-font-family-headings: Open Sans, sans-serif;--mantine-primary-color-filled: var(--mantine-color-orange-filled);--mantine-primary-color-filled-hover: var(--mantine-color-orange-filled-hover);--mantine-primary-color-light: var(--mantine-color-orange-light);--mantine-primary-color-light-hover: var(--mantine-color-orange-light-hover);--mantine-primary-color-light-color: var(--mantine-color-orange-light-color);--mantine-primary-color-0: var(--mantine-color-orange-0);--mantine-primary-color-1: var(--mantine-color-orange-1);--mantine-primary-color-2: var(--mantine-color-orange-2);--mantine-primary-color-3: var(--mantine-color-orange-3);--mantine-primary-color-4: var(--mantine-color-orange-4);--mantine-primary-color-5: var(--mantine-color-orange-5);--mantine-primary-color-6: var(--mantine-color-orange-6);--mantine-primary-color-7: var(--mantine-color-orange-7);--mantine-primary-color-8: var(--mantine-color-orange-8);--mantine-primary-color-9: var(--mantine-color-orange-9);--mantine-color-myColor-0: #fff4e2;--mantine-color-myColor-1: #ffe9cc;--mantine-color-myColor-2: #ffd09c;--mantine-color-myColor-3: #fdb766;--mantine-color-myColor-4: #fca13a;--mantine-color-myColor-5: #fb931d;--mantine-color-myColor-6: #fc8c0c;--mantine-color-myColor-7: #e17900;--mantine-color-myColor-8: #c86a00;--mantine-color-myColor-9: #ae5a00;}:root[data-mantine-color-scheme="dark"]{--mantine-color-anchor: var(--mantine-color-orange-4);--mantine-color-myColor-text: var(--mantine-color-myColor-4);--mantine-color-myColor-filled: var(--mantine-color-myColor-8);--mantine-color-myColor-filled-hover: var(--mantine-color-myColor-9);--mantine-color-myColor-light: rgba(252, 140, 12, 0.15);--mantine-color-myColor-light-hover: rgba(252, 140, 12, 0.2);--mantine-color-myColor-light-color: var(--mantine-color-myColor-3);--mantine-color-myColor-outline: var(--mantine-color-myColor-4);--mantine-color-myColor-outline-hover: rgba(252, 161, 58, 0.05);}:root[data-mantine-color-scheme="light"]{--mantine-color-anchor: var(--mantine-color-orange-6);--mantine-color-myColor-text: var(--mantine-color-myColor-filled);--mantine-color-myColor-filled: var(--mantine-color-myColor-6);--mantine-color-myColor-filled-hover: var(--mantine-color-myColor-7);--mantine-color-myColor-light: rgba(252, 140, 12, 0.1);--mantine-color-myColor-light-hover: rgba(252, 140, 12, 0.12);--mantine-color-myColor-light-color: var(--mantine-color-myColor-6);--mantine-color-myColor-outline: var(--mantine-color-myColor-6);--mantine-color-myColor-outline-hover: rgba(252, 140, 12, 0.05);}\n' +
    '   |  ^'
}

My vite.config.ts:

cjsInterop({
      // List of CJS dependencies that require interop
      dependencies: [/*'lodash','lodash/**',*/
      'lodash',
      'dayjs',
    ],
      client: true,
      apply:'serve'
    }),

Feature request: Dynamic import support

Thanks for writing such a useful plugin.

It looks like it works on static imports:

import { foo } from 'foo';

but what about

import('foo').then(foo => { /*...*/ });

Could it be extended to work for dynamic imports? It's issue that came up for me.

No default export after transformation

I still get the the error for some imports after transformation in the browser.
Any idea on how I can debug this?

ERROR in Browser Console:

react-server-dom-webpack_client.js?v=18063975:866 Uncaught SyntaxError: The requested module '/node_modules/.pnpm/[email protected]/node_modules/lodash/isNumber.js?v=c30a9c6d' does not provide an export named 'default' (at DataUtils.js?v=c30a9c6d:8:8)

vite.config.ts

import { defineConfig } from 'vite';
import { cjsInterop } from 'vite-plugin-cjs-interop';

export default defineConfig(({ mode }) => ({
  ...({
    optimizeDeps: {
      include: ['dayjs','dayjs/**/*'],
      exclude: ['@mantine/core','@mantine/hooks'],
    },
    ssr: {
      noExternal: ['@mantine/core','@mantine/hooks'],
    },
  }),
  plugins: [
    cjsInterop({
      // List of CJS dependencies that require interop
      dependencies: [
      'lodash/**/*',
    ],
      client: true,
      apply:'serve'
    }),
  ],
}));

DataUtils.js?v=c30a9c6d:8:8:

const {default: isString=__cjsInterop4__} = __cjsInterop4__?.default?.__esModule ? __cjsInterop4__.default : __cjsInterop4__;
const {default: isNan=__cjsInterop3__} = __cjsInterop3__?.default?.__esModule ? __cjsInterop3__.default : __cjsInterop3__;
const {default: get=__cjsInterop2__} = __cjsInterop2__?.default?.__esModule ? __cjsInterop2__.default : __cjsInterop2__;
const {default: lodashIsNumber=__cjsInterop1__} = __cjsInterop1__?.default?.__esModule ? __cjsInterop1__.default : __cjsInterop1__;
import __cjsInterop4__ from "/node_modules/.pnpm/[email protected]/node_modules/lodash/isString.js?v=3e84beda";
import __cjsInterop3__ from "/node_modules/.pnpm/[email protected]/node_modules/lodash/isNaN.js?v=3e84beda";
import __cjsInterop2__ from "/node_modules/.pnpm/[email protected]/node_modules/lodash/get.js?v=3e84beda";
import /* Line:8, Character: 8 */__cjsInterop1__ from "/node_modules/.pnpm/[email protected]/node_modules/lodash/isNumber.js?v=3e84beda";
export var mathSign = function mathSign(value) {
    if (value === 0) {
        return 0;
    }
    if (value > 0) {
        return 1;
    }
    return -1;
};
...

This is are some console.log values from the cjs plugin:

  • the cjs-interop-msg document the parameter id and the first 10 characters of code
  • the cjs-interop-fix-id is the node.source.value before pushed to toBeFixed
cjs-interop-msg /Users/ah/SVN-Checkouts/TST/waku-mantine/node_modules/.pnpm/@[email protected]_@[email protected]_@[email protected][email protected][email protected]_ijs54lfvbjpc5kq3mttqn75pb4/node_modules/@mantine/dates/styles.css CODE: "export def"
cjs-interop-msg /Users/ah/SVN-Checkouts/TST/waku-mantine/node_modules/.pnpm/@[email protected]_@[email protected]_@[email protected][email protected][email protected]_ijs54lfvbjpc5kq3mttqn75pb4/node_modules/@mantine/dates/styles.css CODE: "import { u"
cjs-interop-msg /Users/ah/SVN-Checkouts/TST/waku-mantine/node_modules/.pnpm/@[email protected]_@[email protected]_@[email protected][email protected][email protected]_ijs54lfvbjpc5kq3mttqn75pb4/node_modules/@mantine/dates/styles.css CODE: "export def"
cjs-interop-fix-id lodash/isFunction
cjs-interop-fix-id lodash/sortBy
cjs-interop-fix-id lodash/isNil
cjs-interop-fix-id lodash/throttle
cjs-interop-fix-id lodash/isNil
cjs-interop-fix-id lodash/isNil
cjs-interop-fix-id lodash/isFunction
cjs-interop-fix-id lodash/isObject
cjs-interop-fix-id lodash/isNil
cjs-interop-fix-id lodash/isObject
cjs-interop-fix-id lodash/isFunction
cjs-interop-fix-id lodash/last
cjs-interop-fix-id lodash/upperFirst
cjs-interop-fix-id lodash/isFunction
cjs-interop-fix-id lodash/isFunction
cjs-interop-fix-id lodash/upperFirst
cjs-interop-fix-id lodash/maxBy
cjs-interop-fix-id lodash/minBy
cjs-interop-fix-id lodash/isFunction
cjs-interop-fix-id lodash/get
cjs-interop-fix-id lodash/isEqual
cjs-interop-fix-id lodash/isNil
cjs-interop-fix-id lodash/isFunction
cjs-interop-fix-id lodash/isNil
cjs-interop-fix-id lodash/last
cjs-interop-fix-id lodash/first
cjs-interop-fix-id lodash/isEqual
cjs-interop-fix-id lodash/isFunction
cjs-interop-fix-id lodash/isFunction
cjs-interop-fix-id lodash/range
cjs-interop-fix-id lodash/isFunction
cjs-interop-fix-id lodash/isFunction
cjs-interop-fix-id lodash/some
cjs-interop-fix-id lodash/isFunction
cjs-interop-fix-id lodash/isFunction
cjs-interop-fix-id lodash/get
cjs-interop-fix-id lodash/isFunction
cjs-interop-fix-id lodash/isEqual
cjs-interop-fix-id lodash/isFunction
cjs-interop-fix-id lodash/isFunction
cjs-interop-fix-id lodash/isFunction
cjs-interop-fix-id lodash/isNil
cjs-interop-fix-id lodash/isEqual
cjs-interop-fix-id lodash/isFunction
cjs-interop-fix-id lodash/max
cjs-interop-fix-id lodash/isNil
cjs-interop-fix-id lodash/isNaN
cjs-interop-fix-id lodash/isEqual
cjs-interop-fix-id lodash/isEqual
cjs-interop-fix-id lodash/isNil
cjs-interop-fix-id lodash/isNil
cjs-interop-fix-id lodash/isEqual
cjs-interop-fix-id lodash/isFunction
cjs-interop-fix-id lodash/maxBy
cjs-interop-fix-id lodash/min
cjs-interop-fix-id lodash/get
cjs-interop-fix-id lodash/sumBy
cjs-interop-fix-id lodash/isFunction
cjs-interop-fix-id lodash/isFunction
cjs-interop-fix-id lodash/isNumber
cjs-interop-fix-id lodash/isString
cjs-interop-fix-id lodash/omit
cjs-interop-fix-id lodash/isEqual
cjs-interop-fix-id lodash/isNaN
cjs-interop-fix-id lodash/isFunction
cjs-interop-fix-id lodash/omit
cjs-interop-fix-id lodash/get
cjs-interop-fix-id lodash/get
cjs-interop-fix-id lodash/isNil
cjs-interop-fix-id lodash/isString
cjs-interop-fix-id lodash/isFunction
cjs-interop-fix-id lodash/isObject
cjs-interop-fix-id lodash/uniqBy
cjs-interop-fix-id lodash/isFunction
cjs-interop-fix-id lodash/isString
cjs-interop-fix-id lodash/isNaN
cjs-interop-fix-id lodash/get
cjs-interop-fix-id lodash/isNumber
cjs-interop-fix-id lodash/isObject
cjs-interop-fix-id lodash/isNil
cjs-interop-fix-id lodash/max
cjs-interop-fix-id lodash/min
cjs-interop-fix-id lodash/isNil
cjs-interop-fix-id lodash/isFunction
cjs-interop-fix-id lodash/isString
cjs-interop-fix-id lodash/get
cjs-interop-fix-id lodash/flatMap
cjs-interop-fix-id lodash/isNaN
cjs-interop-fix-id lodash/upperFirst
cjs-interop-fix-id lodash/isEqual
cjs-interop-fix-id lodash/sortBy
cjs-interop-fix-id lodash/isFunction
cjs-interop-fix-id lodash/isPlainObject
cjs-interop-fix-id lodash/isBoolean
cjs-interop-fix-id lodash/isEqual
cjs-interop-fix-id lodash/mapValues
cjs-interop-fix-id lodash/every
cjs-interop-fix-id lodash/find
cjs-interop-fix-id lodash/every
cjs-interop-fix-id lodash/isFunction
cjs-interop-fix-id lodash/isNil
cjs-interop-fix-id lodash/isFunction
cjs-interop-fix-id lodash/range
cjs-interop-fix-id lodash/get
cjs-interop-fix-id lodash/sortBy
cjs-interop-fix-id lodash/throttle
cjs-interop-fix-id lodash/memoize

plug-in does not appear to work.. What did I do wrong?

// vite.config.ts
import { resolve } from 'path'

import reactSWC from '@vitejs/plugin-react-swc'
import { defineConfig } from 'vite'
import { cjsInterop } from 'vite-plugin-cjs-interop'
import vitePluginDts from 'vite-plugin-dts'
import tsconfigPaths from 'vite-tsconfig-paths'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    cjsInterop({
      dependencies: ['@emotion/styled', '@emotion/react'],
    }),
    reactSWC({
      jsxImportSource: '@emotion/react',
    }),
    vitePluginDts({
      insertTypesEntry: true,
    }),
    tsconfigPaths({ root: './' }),
  ],
  build: {
    sourcemap: true,
    lib: {
      entry: resolve(__dirname, 'src/main.ts'),
      name: 'MyLib',
      fileName: 'my-lib,
    },
    rollupOptions: {
      external: [
        '@emotion/react',
        '@emotion/styled',
        '@types/react',
        '@types/react-dom',
        'react',
        'react-dom',
        'typescript',
        'react-beautiful-dnd',
      ],
    },
  },
})
// build result
...
var Xa = Object.defineProperty;
var Ja = (e, t, r) => t in e ? Xa(e, t, { enumerable: !0, configurable: !0, writable: !0, value: r }) : e[t] = r;
var lr = (e, t, r) => (Ja(e, typeof t != "symbol" ? t + "" : t, r), r);
import * as Ln from "react";
import Q, { createContext as Qo, forwardRef as Jr, useContext as ei, createElement as nt, Fragment as Qa, useMemo as we, useCallback as F, useState as Y, useRef as Fe, useEffect as _e, useLayoutEffect as Fn, useImperativeHandle as Qr, PureComponent as ti, Children as es } from "react";
import { css as C, useTheme as en, keyframes as Ge, ThemeProvider as ts } from "@emotion/react";
import c from "@emotion/styled";
import ri, { createPortal as rs } from "react-dom";
import { Draggable as ns, Droppable as os, DragDropContext as is } from "react-beautiful-dnd";
function as(e) {
  if (e.sheet)
    return e.sheet;
  for (var t = 0; t < document.styleSheets.length; t++)
    if (document.styleSheets[t].ownerNode === e)
      return document.styleSheets[t];
}
...

here is my vite.config and build result.

I want to unwrap default imports @emotion by using this plugin.
But Doesn't seem to have applied to the build result.

what did i do wrong??

// pacakge.json
"devDependencies": {
    "vite": "^4.0.0",
    "vite-plugin-cjs-interop": "^0.0.7",
    "vite-plugin-dts": "^1.7.1",
    "vite-tsconfig-paths": "^4.0.3",
    "@vitejs/plugin-react-swc": "^3.0.0",
  },

Dependency problem with estree-walker

I'm getting Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: No "exports" main defined in .../node_modules/vite-plugin-cjs-interop/node_modules/estree-walker/package.json

I'm fairly certain this is Rich-Harris/estree-walker#26, but with no solution forthcoming on their side I'm wondering how you got this to work?

Cannot find vite-plugin-cjs-interop or type declarations

Issue

I know this is probably not an issue with this library, but I wanted to check anyways.

With TypeScript 5.3.3 and vite-plugin-cjs-interop 2.0.3, I'm getting the error

Cannot find module 'vite-plugin-cjs-interop' or its corresponding type declarations.
  There are types at 'node_modules/vite-plugin-cjs-interop/dist/index.d.ts', but this result could not be resolved under your current 'moduleResolution' setting. Consider updating to 'node16', 'nodenext', or 'bundler'.ts(2307)

tsconfig.json

{
  "include": ["env.d.ts", "**/*.ts", "**/*.tsx"],
  "compilerOptions": {
    "lib": ["DOM", "DOM.Iterable", "ES2022"],
    "isolatedModules": true,
    "esModuleInterop": true,
    "jsx": "react-jsx",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "target": "ES2022",
    "module": "ES2022",
    "skipLibCheck": true,
    "strict": true,
    "allowJs": true,
    "forceConsistentCasingInFileNames": true,
    "baseUrl": ".",
    "types": ["vitest/globals"],
    "paths": {
      "~/*": ["./app/*"],
      "assets/*": ["./app/src/assets/*"],
      "pages/*": ["./app/src/pages/*"],
      "services/*": ["./app/src/services/*"],
      "utils/*": ["./app/src/utils/*"],
      "components/*": ["./app/src/components/*"],
      "types/*": ["./app/src/types/*"]
    },
    // Remix takes care of building everything in `remix build`.
    "noEmit": true
  }
}

I have another project with an identical tsconfig and cjs-interop plugin version number that does not produce this error.

I don't want to change the moduleResolution because that will mess up other configurations I have with this repo.

I have tried deleting the yarn.lock and the node_modules.

Would anyone have any ideas why vite-plugin-cjs-interop might be producing this error?

Thank you!

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.