'How to turn a .js file into ES6 module when both Webpack and Babel are used?

As title. I have a file that exposes a top-level/global var foo. But I got an error when I ran those production files on Webpack Dev Server, which said that the global variable foo is not defined. In the entry point(this is a term of Webpack) .tsx-file, I've added the following line to import this .js file: (I'm sure that the problem is not on the path alias, @, and indeed I can omit the .js-extension too)

import '@/external/path/to/non_es6_module.js'

Now I'm reading about this: https://babeljs.io/docs/en/babel-plugin-transform-modules-commonjs, i.e. I think babel is related to this problem. But the sample provided in the link is different than my case, i.e. in my case, there is no export in the .js file I want to import:

in

export default 42;

Out

Object.defineProperty(exports, "__esModule", {
  value: true,
});

exports.default = 42;

Some of my reasoning:

One might say that:

Why not just modify the .js-file, i.e. by adding the export keyword, so you can use that Babel plugin to do the transform?

But the problem is that the .js-file that I want to import is a machine-generated file. And I think it's not ideal to manually modify it, since it will be upgraded in the (near) future. I don't want to do this every time!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source