Reputation: 77
So here is my plan. I want to build an application using Typescript for Windows and Mac. However, as I'm gonna transpiling the Typeascript code to Javascript code, I want to achieve some feature if possible. I want to get only Windows code when I want, and only Mac code when I want.
They way I want to do it, or at-least trying, is to use the exclude
in tsconfig.json.
Let's take simple example.
In the root project I would have src
folder. Inside, I would have code.ts
file.
Also: code.darwin.ts
and code.windows.ts
files.
code.darwin.ts:
const Logger = () => {
console.log('DARWIN');
}
export default Logger;
code.windows.ts:
const Logger = () => {
console.log('WINDOWS');
}
export default Logger;
code.ts:
import Logger from './code.darwin';
import Logger from './code.windows';
Logger();
In this example, if I want only mac code I'd use tsconfig.json:
{
"compilerOptions": {
"target": "ES2017", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
"outDir": "./dist", /* Redirect output structure to the directory. */
"rootDir": "./src", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
"strict": true, /* Enable all strict type-checking options. */
"alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
"typeRoots": ["./node_modules/@types"], /* List of folders to include type definitions from. */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
"skipLibCheck": true, /* Skip type checking of declaration files. */
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
},
"exclude": ["**/*.windows.ts"],
}
But yet, I have ts clash error in code.ts
because I import same thing from 2 files. Any idea how to resolve it?
The way I do it is not a must. I'm open to other suggestions using Typescript. The most important thing is that I'll be able to get only 1 OS platform code finally.
Upvotes: 3
Views: 803
Reputation: 1824
You can use dynamic import feature of Typescript.
You should use process.platform
in order to get it work.
Edit your code.ts file to:
import(`./code.${process.platform}`).then((logger) => {
logger();
});
Keep all other files the same.
Note the import expression. Adjust it to your needs.
Upvotes: 2