0

I use the following (ES5) code to currently import a module and call it as a function (where ... represents some arguments):

var rimraf = require("rimraf")
rimraf(...)

I would like to utilise ES6's import with my code so I have tried the following ways:

import * as rimraf from "rimraf"
import rimraf from "rimraf"

These are the ways to import that I have read about in various places, however each time I attempt to call rimraf(...) I get the error ReferenceError: rimraf is not defined.

Apologies if I'm just being stupid, but what is the correct way to implement my import?

Zak
  • 1,910
  • 3
  • 16
  • 31
  • If your module is not a package in the /node_modules/ directory you need to specify the relative route of the module i.e. `import rimraf from './rimraf'` – Efemorav Apr 17 '18 at 22:35
  • `import rimraf from "rimraf"; rimraf(...);` should work fine. – loganfsmyth Apr 17 '18 at 22:36
  • My package is in the `node_modules` folder, see https://github.com/isaacs/rimraf. – Zak Apr 17 '18 at 22:36
  • yeah, it should work fine then – Efemorav Apr 17 '18 at 22:36
  • I thought so too, but it doesn't seem to...as in my question only the ES5 method works, I get the error when using the suggestion from @loganfsmyth. – Zak Apr 17 '18 at 22:37
  • I think we'd need a reproducible example somewhere then, since the code provided should work. You also haven't specified, but are you using Babel to compile the modules, or what? – loganfsmyth Apr 17 '18 at 22:59
  • The equivalent syntax of your first example is `import rimraf from 'rimraf'`, if that's what you're asking. I'm not sure how babel handles it, but I know the `--experimental-modules` flag handles it that way. – jhpratt Apr 17 '18 at 23:15

2 Answers2

0

Node doesn't support import syntax as of v9.11.1. In order to use that you'd need to setup/use something like babel, Typescript to compile. Alternatively you can follow the instructions in the link above to enable experimental support.

Kevin Peno
  • 9,107
  • 1
  • 33
  • 56
  • Thanks for the answer – I am using Babel (so using full ES6). Sorry if this wasn't clear. – Zak Apr 17 '18 at 23:11
  • The Question doesn't state you are using any pre-processor. If you are, as you say, we'll need something to duplicate with. – Kevin Peno Apr 17 '18 at 23:55
0

I had to import it like this

import * as rimraf from "rimraf"

and then use it like this

rimraf.rimraf(dir)

For example,

const clean = async () => rimraf.rimraf(dir);
await clean();

I'm using "rimraf": "^5.0.1" and node v17.6.0

hfc
  • 614
  • 1
  • 5
  • 13