137

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?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Ben Hadfield
  • 1,371
  • 2
  • 9
  • 6
  • What transpiler are you using? Have you tried it? – Bergi Jan 09 '17 at 17:16
  • 1
    Possible duplicate of [NodeJS plans to support import/export es6 (es2015) modules](http://stackoverflow.com/questions/37132031/nodejs-plans-to-support-import-export-es6-es2015-modules) – Sam Hanley Jan 09 '17 at 17:16

5 Answers5

266

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).

Michel
  • 26,600
  • 6
  • 64
  • 69
  • 3
    In my case, besides doing `npm install --save-dev @types/node`, I also had to update my `tsconfig.json` and add `node` under `compilerOptions` --> `types`. – hfc Apr 20 '22 at 08:56
  • Is this preferred over `import path from "path"`? – Elijah Mock Jul 29 '23 at 00:35
24

If not using typescript

import * as path from 'path'

is the only thing that works for me.

Dharman
  • 30,962
  • 25
  • 85
  • 135
  • 2
    Thanks for your contribution, but look at Michael P. Bazos answer, he did mention that part aswell – Areg Jun 01 '21 at 17:12
  • 3
    Thanks Dharman, I thought it was appropriate to indicate this works with javascript, as Michael answer is specifically referring to Typescript. – Ricardo Rabanales Jun 02 '21 at 19:24
15
import path from 'path';

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

Cyril Gupta
  • 13,505
  • 11
  • 64
  • 87
  • 2
    Need to add `"type": "module"` to `package.json`. Also add `"esModuleInterop": true` in `tsconfig.json`. https://stackoverflow.com/a/37132668/69746 – Xolve Dec 30 '21 at 09:11
  • 1
    I keep coming back here several times a year! – MEMark Sep 30 '22 at 12:35
14

You can either do

import module from 'path'

or if you just need to import path just do

import 'path'

G4bri3l
  • 4,996
  • 4
  • 31
  • 53
2

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.

Paul
  • 35,689
  • 11
  • 93
  • 122