karamon14
karamon14

Reputation: 41

Babel 7 - node static class method is undefined

I'm trying to use babel 7 to compile a simple ES6 module (library) with a static function inside.

// src/index.js
class YtUrl {
    static extractIdFromUrl(url) {
        const regExp = /^.*(?:(?:youtu\.be\/|v\/|vi\/|u\/\w\/|embed\/)|(?:(?:watch)?\?v(?:i)?=|\&v(?:i)?=))([^#\&\?]*).*/
        const [, videoID] = url.match(regExp)
        return videoID
    }
}

Import the compiled module into a js node file for testing

const YtUrl = require('./dist/index')
console.log(YtUrl).                 // { default: [Function: YtUrl] }
console.log(YtUrl.extractIdFromUrl) // undefined
// usage: YtUrl.extractIdFromUrl('https://wwww.youtube.com/....')

But the static method is undefined. The following is my package.json

"scripts": {
  "build": "rm -rf dist && babel src --out-dir dist",
  "test": "echo \"Error: no test specified\" && exit 1"
},
"devDependencies": {
  "@babel/cli": "^7.11.6",
  "@babel/core": "^7.11.6",
  "@babel/plugin-proposal-class-properties": "^7.10.4",
  "@babel/preset-env": "^7.11.5"
}

And here is the .babelrc file

{
  "presets": [
    [
      "@babel/preset-env",
      {
        "useBuiltIns": "usage",
        "corejs": "3"
      }
    ]
  ],
  "plugins": ["@babel/plugin-proposal-class-properties"]
}

Upvotes: 0

Views: 321

Answers (1)

Felix Kling
Felix Kling

Reputation: 816590

The static method exists, but you are accessing the wrong value.

console.log(YtUrl) shows that the value of YtUrl is an object with a default property, not a function:

{ default: [Function: YtUrl] }

That means the class is available at YtUrl.default:

console.log(YtUrl.default.extractIdFromUrl)

When using ES modules in a CommonJS context, default exports are usually available at the default property of the module object.

Upvotes: 1

Related Questions