2021年1月18日星期一

Nodejs - import stuff from mjs file into js file OR how to use require in mjs file?

I am new to JS and Node. From what I been reading it seems like ES6 import is not supported in Node so I am forced to use experiment mode (renaming my file to mjs)

This works for the most part unless the mjs file needs to use require. My current solution is to break out the chunk of code that depends on require to a seperate .js file and import that js file

foo.mjs

import readFileSync from './util.js'  ...   //orignally just do require('fs') and do fs.readFileSync()  const configFile = readFileSync(configFilePath);    

util.js

const fs = require('fs');  const path = require('path');    function readFileSync(filePath) {    console.log(__dirname)    console.log(path.resolve(__dirname, filePath))    return fs.readFileSync(path.resolve(__dirname, filePath), 'utf8');  }    module.exports = readFileSync    

Is there a way I can avoid doing this? My app.js has lots of require and I don't want to break out all those parts into separate js files.

I tried changing require to import

// const express = require('express');  import * as express from 'express';  

but when run node --experimental-modules app.mjs

I get an error

TypeError: express is not a function  

I think I need to either

  • find a way to use require in mjs
  • or find a way to import stuff in mjs into a js file
https://stackoverflow.com/questions/65784124/nodejs-import-stuff-from-mjs-file-into-js-file-or-how-to-use-require-in-mjs-fi January 19, 2021 at 08:58AM

没有评论:

发表评论