node-ytdl-core icon indicating copy to clipboard operation
node-ytdl-core copied to clipboard

ESModules?

Open jonahsnider opened this issue 4 years ago • 4 comments

I'd like to use certain functions from the package (mostly just the util functions for validation) in a frontend Next.js app. Since the package is currently being exported using CommonJS, no tree-shaking can occur.

This means anyone who visits the site would download the entire ytdl-core package even though only a small fraction of it is being used.

If ytdl-core offered ECMAScript modules exports (in addition to CommonJS) bundle sizes can be optimized on the web.

jonahsnider avatar Jun 07 '20 17:06 jonahsnider

does import util from 'ytdl-core/lib/util work?

fent avatar Jun 07 '20 20:06 fent

I believe that'll work better, now it's importing less code, but still being wasteful. Unfortunately doing this breaks TypeScript compilation:

Could not find a declaration file for module 'ytdl-core/lib/util'. '/usr/src/project/node_modules/ytdl-core/lib/util.js' implicitly has an 'any' type.
  Try `npm install @types/ytdl-core` if it exists or add a new declaration (.d.ts) file containing `declare module 'ytdl-core/lib/util';`

A hacky fix can be done like this:

import {getVideoID as _getVideoID, validateURL as _validateURL} from 'ytdl-core';
// @ts-ignore
import ytdlUtil from 'ytdl-core/lib/util';

const {validateURL, getVideoID} = ytdlUtil as {validateURL: typeof _validateURL; getVideoID: typeof _getVideoID};

jonahsnider avatar Jun 08 '20 06:06 jonahsnider

ah, well I plan on converting this library to ts in the future, which will generate definitions for each source file

otherwise, there's this guide https://nodejs.org/api/esm.html#esm_dual_commonjs_es_module_packages

fent avatar Jun 08 '20 15:06 fent

A rewrite seems like the only feasible way to do this. Looking forward to when that's released. You might find this useful for getting started with that.

jonahsnider avatar Jun 08 '20 17:06 jonahsnider