vueuse / gesture

🕹 Vue Composables making your app interactive
https://gesture.vueuse.org
MIT License
353 stars 18 forks source link

Add "types" to "exports" in package.json #23

Open thomasaull opened 1 year ago

thomasaull commented 1 year ago

VS Code is complaining about a "wrong" configuration when using this package in a TypeScript project:

Could not find a declaration file for module '@vueuse/gesture'. '[…]/node_modules/.pnpm/@vueuse+gesture@2.0.0-beta.1_vue@3.3.4/node_modules/@vueuse/gesture/dist/index.mjs' implicitly has an 'any' type. There are types at '[…]/node_modules/@vueuse/gesture/dist/index.d.ts', but this result could not be resolved when respecting package.json "exports". The '@vueuse/gesture' library may need to update its package.json or typings.ts(7016)

It can be easily fixed by adding a reference to the types to the exports section:

"exports": {
  ".": {
    "import": "./dist/index.mjs",
    "require": "./dist/index.cjs",
    "types": "./dist/index.d.ts"
  }
},
happy-turtle commented 7 months ago

Related to https://github.com/vueuse/gesture/pull/25

armenr commented 6 months ago

For anyone that's getting bitten by this, until the maintainer can patch it up - I made this quick & dirty fix-it script.

It's supposed to run as a post-install script in your project's package.json

// util/scripts/post-install-hooks/postInstall.cjs
const fs = require('fs');
const path = require('path');
const packageJsonPath = path.resolve(__dirname, '../../../node_modules', '@vueuse', 'gesture', 'package.json');

// Function to check if the required entry exists in package.json
function checkPackageJson() {
  try {
    const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));

    if (packageJson.exports && packageJson.exports['.'] && packageJson.exports['.'].types === './dist/index.d.ts') {
      console.log('Required entry already exists in package.json.');
      return true;
    }
  } catch (error) {
    console.error('Error reading package.json:', error);
    return false;
  }

  return false;
}

// Function to update package.json with the required entry
function updatePackageJson() {
  try {
    const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));

    if (!packageJson.exports) {
      packageJson.exports = {};
    }

    if (!packageJson.exports['.']) {
      packageJson.exports['.'] = {};
    }

    packageJson.exports['.'].types = './dist/index.d.ts';

    fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));
    console.log('package.json updated successfully.');
  } catch (error) {
    console.error('Error updating package.json:', error);
  }
}

// Run the post-install script
if (!checkPackageJson()) {
  updatePackageJson();
}

In your package.json

...

    "postinstall": "node util/scripts/post-install-hooks/postInstall.cjs",

---