Answer a question

i stared to java script coding on vs code editor,when i tried to include the external module into my project, the code editor suggest this -->(File is a CommonJS module; it may be converted to an ES6 module.).. is there any way to fix this issue with commend line?my code

Answers

Right now the only stable supported module system inside nodejs is commonjs, which is the module system based on the require function and the module global object.

The support to the es6 module system is considered an unstable feature of node, which basically means that the community could decide to change it by introducing breaking changes without respecting the semantic versioning.

So, you basically have 3 choices when it comes to chosing a module system for nodejs:

  • stick with commonjs modules and wait for the es6 modules support to become a stable feature
  • use the currently supported unstable api for es6 modules
  • use es6 modules in your code and, then, use babel to transpile back to commonjs modules so that node can run the transpiled code by using stable apis only

In my opinion the simplest and most effective choice is sticking to commonjs and wait for the es6 module support to become a stable api. At that point, you can safely switch to es6 modules. I would avoid to add complexity by setting up babel and a build process to transpile es6 modules to commonjs modules.

This means that, right now, you can safely ignore that warning in VS code. VS code is hinting you to switch to es6 modules because they have been designed to be the universal module system for javascript, but the adoption process takes time to complete as you can imagine.

There is actually a fourth alternative, but it requires you to adopt typescript (which is, by the way, a good choice for medium to large size projects): write your source code with typescript and let the typescript compiler to transpile it back to node-compatible javascript code.

Typescript uses the es6 module system out of the box, so by adopting typescript you will work with the es6 module system right from the start.

Logo

开发云社区提供前沿行业资讯和优质的学习知识,同时提供优质稳定、价格优惠的云主机、数据库、网络、云储存等云服务产品

更多推荐