JamieCurnow / vue-clipboard3

Easily copy to clipboard in Vue 3
MIT License
129 stars 13 forks source link

[ERR_REQUIRE_ESM]: Must use import to load ES require() of ES modules is not supported #7

Open wocwin opened 2 years ago

wocwin commented 2 years ago

image

JamieCurnow commented 1 year ago

@wocwin Could you create a minimal reproduction please? I've installed in a fresh vue project with vite and with webpack and all seems to be working.

sthwang-metal commented 1 year ago

I ran into a similar issue when using vitest and vue-test-utils to mount a component (using composition API) in a test that has import useClipboard from "vue-clipboard3" :

ReferenceError: exports is not defined in ES module scope This file is being treated as an ES module because it has a '.js' file extension and '/Users/sthwang/github/governor/governor-ui/node_modules/vue-clipboard3/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.

It seems that for some reason my vitest loads both the cjs and esm distribution when it should use the esm.

Changing this library's package.json to use conditional exports fixes my issue as seen here https://nodejs.org/api/packages.html#approach-1-use-an-es-module-wrapper.

ie.

  "exports": {
    "import": "./dist/esm/index.js",
    "require": "./dist/cjs/index.js"
  },

An alternative fix I have is to include resolve: { mainFields: ['module'] } in my vitest.config.ts ie.

defineConfig({
  ...
  resolve: {
    mainFields: ['module']
  }
  ...
})

This is probably likely to how my configs are setup, but hopefully this is useful to anyone running into the same issue.

abnormalboy commented 9 months ago

I ran into a similar issue when using vitest and vue-test-utils to mount a component (using composition API) in a test that has import useClipboard from "vue-clipboard3" :

ReferenceError: exports is not defined in ES module scope This file is being treated as an ES module because it has a '.js' file extension and '/Users/sthwang/github/governor/governor-ui/node_modules/vue-clipboard3/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.

It seems that for some reason my vitest loads both the cjs and esm distribution when it should use the esm.

Changing this library's package.json to use conditional exports fixes my issue as seen here https://nodejs.org/api/packages.html#approach-1-use-an-es-module-wrapper.

ie.

  "exports": {
    "import": "./dist/esm/index.js",
    "require": "./dist/cjs/index.js"
  },

An alternative fix I have is to include resolve: { mainFields: ['module'] } in my vitest.config.ts ie.

defineConfig({
  ...
  resolve: {
    mainFields: ['module']
  }
  ...
})

This is probably likely to how my configs are setup, but hopefully this is useful to anyone running into the same issue.

I have encountered the same problem with vtu and your method is very effective