Can you import node's path module using import path from 'path'

Javascriptnode.jsEs6 Modules

Javascript Problem Overview


I prefer using the import x from 'y' syntax, but all I've seen online is const path = require('path').

Is there a way to import the path module using this syntax?

Javascript Solutions


Solution 1 - Javascript

For people trying to import path in a TypeScript file, and ending up here:

  1. Be sure to have node types installed:

     npm install --save-dev @types/node
    
  2. Import path symbol:

     import * as path from 'path';
    

Note: @types/* are automatically included for compilation, providing you use typescript version 2.0 or above, and provided you don't override the types property in compiler options file (tsconfig.json).

Solution 2 - Javascript

You can either do

import module from 'path'

or if you just need to import path just do

import 'path'

Solution 3 - Javascript

If not using typescript

import * as path from 'path'

is the only thing that works for me.

Solution 4 - Javascript

import path from 'path';

As of now, this is the code that's working for me in typescript.

Solution 5 - Javascript

If the version of nodejs you're using supports the ES 6 features, then yes. Otherwise not. Most of the older versions (pre 6.x if memory serves but you should check for your version) required the --harmony flag in order to do this, the latest releases include it natively.

For this reason, and because it works in all versions, most online resources still use the require syntax.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBen HadfieldView Question on Stackoverflow
Solution 1 - JavascriptMichael P. BazosView Answer on Stackoverflow
Solution 2 - JavascriptG4bri3lView Answer on Stackoverflow
Solution 3 - JavascriptRicardo RabanalesView Answer on Stackoverflow
Solution 4 - JavascriptCyril GuptaView Answer on Stackoverflow
Solution 5 - JavascriptPaulView Answer on Stackoverflow