Importing a Node/JS, require/import, module/commonjs module

I'm trying to get through to importing modules.

Desire: use require and import regardless of the module type (module_es6/commonjs) without additional libraries.

enter a description of the image here

In directories (image) demo-* - export
In directories import-as-* - import what is in demo-*

Modules *-commonjs are described in the style module.exports/require
Modules *-module are described in the style export/import
Example:

// "type": "commonjs"
module.exports = () => {
    return "i commonjs"
}
// "type": "module"
export default () => {
    return "i module"
}

In each package.json, the corresponding value is added property "type": "module/commonjs"
Example:

{
    "name": "demo-module",
    "main": "./index.js",
    "type": "module"
}

Node (- v v12.13.0) starts with the flag --experimental-modules and --es-module-specifier-resolution=node

Everything is fine with importing from import-as-module, including the module demo-commonjs.
But from import-as-commonjs does not import anything from require('../demo-module').

Error [ERR_REQUIRE_ESM]:  
Must use import to load ES Module: ...path.../demo-module/index.js

How to achieve the desired result?

Below is an impossible snippet!!!

// + ПРИМЕРЫ ЭКСПОРТА

// demo-commonjs | package.json->{name, main,"type": "commonjs"}
module.exports = () => {
    return "i commonjs"
}

// demo-module | package.json->"type": "module"
const CONST_MOD = 'CONST_MOD'
export { CONST_MOD }
export default () => {
    return "i module"
}


// + ПРИМЕРЫ ИМПОРТА

// import-as-module | package.json->"type": "module"
import CommonJS from '../demo-commonjs'
console.log(CommonJS())
import def, { CONST_MOD } from '../demo-module'
console.log(def())
console.log(CONST_MOD)

// import-as-commonjs | package.json->"type": "commonjs"
const CommonJS = require('../demo-commonjs')
console.log(CommonJS())
// ЗДЕСЬ ПОЛУЧАЮ ОШИБКУ
try {
    var CONST_MOD = require('../demo-module')
}
catch (error) {
    console.error(error) // Must use import to load ES Module:
}
console.log(CONST_MOD) // undefined
Author: Alexander Lonberg, 2019-10-23

1 answers

Https://nodejs.org/dist/latest-v12.x/docs/api/esm.html#esm_code_require_code

require always treats the files it references as CommonJS.

So your wish is impossible.

 0
Author: Alexey Ten, 2019-10-24 09:49:31