Using import fs from 'fs'

走远了吗. 提交于 2019-12-20 09:48:01

问题


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?


回答1:


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:

const fs = require('fs');



回答2:


For default exports you should use:

import * as fs from 'fs';

Or in case the module has named exports:

import {fs} from 'fs';

Example:

//module1.js

export function function1() {
  console.log('f1')
}

export function function2() {
  console.log('f2')
}

export default function1;

And then:

import defaultExport, { function1, function2 } from './module1'

defaultExport();  // This calls function1
function1();
function2();

Additionally, you should use webpack or something similar to be able to use es6 import




回答3:


In order to use import { readFileSync } from 'fs', you have to:

  1. Be using node 10+
  2. Use the --experimental-modules flag (in node 10), e.g. node --experimental-modules server.mjs (see #3 for explanation of .mjs)
  3. Rename the file extension of your file with the import statements, to .mjs, .js will not work, e.g. server.mjs

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

Here's the node 10 ESM documentation




回答4:


Building on RobertoNovelo's answer:

import * as fs from 'fs';

is currently the simplest way to do it.

Tested with a node project (node v10.15.3), with esm (https://github.com/standard-things/esm#readme) allowing to use import.




回答5:


The new ECMAScript module support is able natively in Node.js 12 🎉

It was released yesterday (2019-04-23) and it means there is no need to use the flag --experimental-modules.

To read more about it: http://2ality.com/2019/04/nodejs-esm-impl.html




回答6:


If we are using TypeScript, we can update the Type definition file by running the command npm install @types/node from the terminal/command prompt.




回答7:


It's not supported just yet.... If you want to use you will have to install babel

https://babeljs.io/docs/setup/



来源:https://stackoverflow.com/questions/43622337/using-import-fs-from-fs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!