cbdeveloper
cbdeveloper

Reputation: 31495

How to know if an npm package can be imported with ES6 import syntax?

Besides going through the documentation of the package and trial/error attempts, how can I know for sure if an npm packaged can be imported with the ES6 import syntax?

Is there a file inside the package folder that I can check?

I constantly question myself about this.

For example:

The md5 package DOCS only mentions md5 = require('md5'); but I've just tested and it works with import md5 from 'md5'

How can I inspect the package and know for sure?

Upvotes: 4

Views: 1544

Answers (2)

user13629438
user13629438

Reputation:

You must check if the module/package has a dist or a src folder. If the package has a dist folder, Then it can be imported using es6's import statement. Otherwise if it has a src folder, Then it can't be imported using es6's import statement and you must use cjs's require function to import such modules. If you try to import a cjs module using the import statement, You will get the following error:

Syntax Error: Cannot use import statement outside a module

Upvotes: 3

Patrick Hund
Patrick Hund

Reputation: 20276

Since you are using Babel and webpack, you can always use import. Webpack is taking care of transpiling the import statements in your code to include the code from the npm packages. I can't think of any case where import would not work while require would.

Upvotes: 4

Related Questions