Hi!
This is a great question, but it’ll require a bit of explanation. I’ll try to keep it as short as possible.
First off, let me say that it’s definitely not wrong to use CommonJS. The full answer, especially if you want to use TypeScript, is a bit more complicated, though.
Transpiling
TypeScript code gets translated into JavaScript code. This process is called transpiling. The TypeScript compiler (tsc) can do this for you. It can also do a lot more, like type checking, but that’s not important for this discussion.
Here’s the catch: the tsc compiler can output JavaScript code in two different formats: CommonJS and ES modules no matter what style is used in the input file. The format is determined by the module
compiler option (specified in a tsconfig.json
).
This means that you can write TypeScript code that uses ES modules, but the output will still be CommonJS. This is what the module
option does: it tells the compiler what format to use for the output.
Example
Let’s say you have a TypeScript file called index.ts
that looks like this:
import { storage } from 'uxp';
console.log(storage) // for demo purposes
Let’s say TypeScript is configured like this:
{
"compilerOptions": {
"module": "esnext"
}
}
When you run tsc index.ts
, the compiler will output a file called index.js
that looks like this:
import { storage } from 'uxp';
console.log(storage); // for demo purposes
Notice that the output is still using ES modules, even though the input is TypeScript. This is because the module
option tells the compiler to use ES modules for the output.
This won’t work since UXP modules need to be imported using the CommonJS require
function!
If you change the module
option to commonjs
, the output will look like this:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const uxp_1 = require("uxp");
console.log(uxp_1.storage); // for demo purposes
As you can see, even though our input file used the ES module syntax (import
), the output is using the CommonJS syntax (require
). This is because the module
option tells the compiler to use CommonJS for the output.
ESLint
Since ESLint is a linter, it doesn’t care about the output format. It only cares about the input format. Its job is to check your code for errors and style issues. It doesn’t care about the output format, because it doesn’t care about the output at all.
Conclusion
For ESLint, you should specify the input format. If you’re using JavaScript, you should use CommonJS (to be able to import UXP modules). If you’re using TypeScript, you can write your code as either CommonJS or ES modules. It doesn’t matter, because the output will be “conformed” by the transpiler. Just make sure that you configure the transpiler to output to CommonJS modules.
I hope this helps! If not all of it makes sense to you, don’t worry. It takes a bit of time to get used to all of this. But it’s worth it (at least in my opinion)!
Happy coding!
Zuri