Search code examples
javascriptnode.jsecmascript-6es6-modulescommonjs

Convert require() without assignment to import


file1.js

console.log("foo")

file2.js

require("./file1")
➜ node file2.js
foo

How would I convert file2.js's require to import and keep the same logic (so no assignment)?


Solution

  • You can use like below, this will import file1 to file2

    import './file1';
    

    This is useful when you want to execute the file1 code but does not want to assign it to the variable. ex:

    • create a database connection if you don't need a connection object.
    • TypeScript compiler generates JavaScript completely without a module definition.