简体   繁体   中英

Is there a way to get the extension's settings (defined in package.json) at runtime?

In a Visual Studio Code extension, is there a way to get the extension's settings (defined in package.json) at runtime? There are a few values (like displayName) that I'd like to get.

A Visual Studio Code extension is written in JavaScript and no different from a standard Node script, so generally speaking you can use fs.readFile to read the extension manifest and JSON.parse to read its values.

Depending on your use-case there might be simpler options.

require()

To read your own extension's package.json , you could simply use require()

Example:

// lib/extension.js
const meta = require('../package.json')

import

The same as above is possible with an import , at least when using TypeScript.

Example :

// src/extension.ts
import * as meta from '../package.json'

Make sure to add a type declarations for JSON files

// src/index.d.ts
declare module '*.json' {
    const value: any;
    export default value;
}

Node dependency

Last but not least, you can read any extension's package.json programmatically. Using a Node packages such as vscode-read-manifest , read-pkg (or read-pkg-up ) make it easy.

Example:

const readManifest = require('vscode-read-manifest');

// Async
(async () => {
    let manifest = await readManifest('ms-python.python');
})();

// Sync
let manifest = readManifest.sync('ms-python.python');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM