I understand the question specifically asked for import ES6 in Node.js, but the following may help others find a more general solution:
let variableName = "es5.js"; const something = require('./utils/${variableName}');
Please note: if you import the ES6 module and you need access to export by default , you will need to use one of the following:
let variableName = "es6.js"; // Assigning const defaultMethod = require('./utils/${variableName}').default; // Accessing const something = require('./utils/${variableName}'); something.default();
You can also use destructuring with this approach, which can add more syntax to your other imports:
// Destructuring const { someMethod } = require('./utils/${variableName}'); someMethod();
Unfortunately, if you want to access by default as well as destructuring, you need to do this in a few steps:
// ES6 Syntax Import defaultMethod, { someMethod } from "const-path.js"; // Destructuring + default assignment const something = require('./utils/${variableName}'); const defaultMethod = something.default; const { someMethod, someOtherMethod } = something;
MCTaylor17 Jan 03 '19 at 19:42 2019-01-03 19:42
source share