Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save scmx/de7564c9efebaec108cfb74e83ec9d1b to your computer and use it in GitHub Desktop.
Save scmx/de7564c9efebaec108cfb74e83ec9d1b to your computer and use it in GitHub Desktop.
VSCode settings.json typescript.tsdk double backslash windows workaround Next.js

VSCode settings.json typescript.tsdk double backslash windows workaround Next.js

VSCode does not provide a way to have OS specific .vscode/settings.json for a project. microsoft/vscode#5595

Next.js adds property to it with a value that needs to be different for windows:

  • macOS/Linux "typescript.tsdk": "node_modules/typescript/lib"
  • Windows "typescript.tsdk": "node_modules\\typescript\\lib"

This is problematic when you want the file to be shared and tracked by version control.

Here's one way to solve this. Rename the file and write a script that generates the file to have correct path separators. See below for a way to do this with Next.js when server starts.

- .vscode/settings.json`
+ .vscode/settings.edit.here.json`
  {
-   "typescript.tsdk": "node_modules\\typescript\\lib",
+   "typescript.tsdk": "node_modules/typescript/lib",
	  "typescript.enablePromptUseWorkspaceTsdk": true,

config/vscodeSettings.js

const { spawnSync } = require('node:child_process');
const fs = require('node:fs');
const path = require('node:path');

/**
 * Generates .vscode/settings.json from .vscode/settings.edit.here.json
 * So that typescript.tsdk can have double backslash on windows
 */

const example = path.join(__dirname, '../.vscode/settings.edit.here.json');
const real = path.join(__dirname, '../.vscode/settings.json');

const exampleJson = JSON.parse(fs.readFileSync(example, 'utf-8'));
exampleJson['typescript.tsdk'] = exampleJson['typescript.tsdk'].replace(/\//g, path.sep);

const generated = `// GENERATED, edit settings.example.json instead and restart server
${JSON.stringify(exampleJson, null, '\t')}`;

fs.writeFileSync(real, generated);

spawnSync('npx', ['prettier', '--quiet', '--write', '.vscode'], { shell: true });

next-config.js

if (process.env.NODE_ENV !== 'production') require('./config/vscodeSettings.js');
...

Time to ignore it from git .gitignore

.vscode/settings.json

Now run next dev and the settings.json should be generated with correct path separators.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment