I want to use import fs from 'fs'
in JavaScript. Here is a sample:
import fs from 'fs'
var output = fs.readFileSync('someData.txt')
console.log(output)
The error I get when I run my file using node main.js
is:
(function (exports, require, module, __filename, __dirname) { import fs from 'fs
'
^^^^^^
SyntaxError: Unexpected token import
What should I install in node in order to achieve importing modules and functions from other places?
ES6 modules support in node.js is fairly recent; even in the bleeding-edge versions, it is still experimental. With node 10, you can start node with the
--experimental-modules
flag, and it will likely work.To import on older node versions - or standard node 10 - use CommonJS syntax:
It's not supported just yet.... If you want to use you will have to install babel
https://babeljs.io/docs/setup/
For default exports you should use:
Or in case the module has named exports:
Example:
And then:
Additionally, you should use webpack or something similar to be able to use es6
import
In order to use
import { readFileSync } from 'fs'
, you'll have to do the following:node 10+
--experimental-modules
flag (in node 10), e.g. node --experimental-modules server.mjs (see #3 for explanation of .mjs)import
statements, to.mjs
, .js will not work, e.g. server.mjsThe other answers hit on 1 and 2, but 3 is also necessary. Also note that this feature is considered extremely experimental at this point (1/10 stability) and not recommended for production... but I will still probably use it in prod :D
Here's the node 10 esm documentation, please like and accept my answer as it's the only correct one :D:D