I am trying to update setting.json from my vs code extension and I want to add below code
"files.associations": {
"*.app": "auraComponent"
}
In other words I want to add below key value pair from extension to the users who are going to install my app
So I tried putting the below code in extension.js but it didn't update the settings.
import { ConfigurationTarget, workspace } from 'vscode';
const configuration = workspace.getConfiguration('files.associations');
configuration.update('.app', 'auraComponent', ConfigurationTarget.Global).then(() => {
// take action here
});
Could someone please suggest if I am using the right approach to update the user or workspace settings and also if the code inside extension.js would be executed automatically or not.
Update
I have added extension.js and included the js code as mentioned by mark in his answer
and update my package.json as below
"main": "./extension",
"activationEvents": [
"*"
],
If I run my extension on debug mode then it works fine but not working in real time.
The below works whether there is a pre-existing files.association setting or not. If there is already one, the new association is added to it (and so may be located somewhere other than the end of the settings file - otherwise a wholly new files.associations setting will be added to the very end of the settings.json file..
const fileConfiguration = vscode.workspace.getConfiguration('files');
const associations = fileConfiguration.get('associations');
associations['*.app'] = "auraComponent";
fileConfiguration.update('associations', associations, vscode.ConfigurationTarget.Global).then(() => {
// take action here
});
Adapted from https://stackoverflow.com/a/49566662/836330.
As explained there, what you really want to update is the associations object, that is the value to be updated. "*.app": "auraComponent is not a configuration key. files.associations is the key and there is an object {...} which is its value.
Related
EDIT: Additional addition of code for task execution
I have a question I can't answer. I need gulp to execute a stain even if the file is unchanged. Currently only when I change my source file it recreates the new destination file. But I would like it to create it even if it hasn't changed. Thank's you in advance :)
Library external : "gulp-inject-string": "^1.1.2",
// Add timestamp in cache PWA
function pwa_cache() {
return src(`${paths.pwa}/serviceworker.tmp.js`)
.pipe(inject.prepend('const CACHE_VERSION = "pwa-v-'+ new Date().getTime() +'"; \n'))
.pipe(rename('serviceworker.js'))
.pipe(dest(`${paths.js}/pwa/`,{overwrite:true}))
}
// Generate all assets
const generateAssets = parallel(
styles,
scripts,
pwa_cache,
imgCompression
)
exports.default = series(generateAssets)
exports["generate-assets"] = generateAssets
Are you maybe running this task within a gulp.watch() ? If so, you'd need to stop the watch task and re-run it.
well I proceeded differently, if it can help someone, it's the only way I found and I don't have time to find another solution.
Instead of adding I rather assign the variable in my file and then I change its value, and I no longer work on a template file but directly on the original file.
Post and link that helped me find the answer: https://eureka.ykyuen.info/2015/07/13/gulp-rewrite-source-files-instead-of-creating-new-files/, How to inject variable value into JS file from GULP, Inject variable into html via Gulp Task
gulp file :
// Add timestamp in cache PWA
function pwa_cache() {
return src(`${paths.js}/pwa/serviceworker.js`, {base: './'})
.pipe(sourcemaps.init())
.pipe(replace(new RegExp('django-pwa-v-\\d*', 's'), 'django-pwa-v-'+ new Date().getTime()))
.pipe(sourcemaps.write('./'))
.pipe(dest('./'))
}
js file :
// Cache version don't touch string assigned to the variable /
CACHE_VERSION = "django-pwa-v-1580491632502";
/////////////////////////////////////////////////////////////
Whilst this question is related to Workbox and Webpack, it does not require any prior knowledge of either library.
Background (skip if not familiar with Workbox)
I am currently utilising the InjectManifest plugin from Workbox 4.3.1 (workbox-webpack-plugin). This version of the library offers an option called manifestTransforms, but unfortunately, the transformations are not applied to assets within the webpack compilation (this is a known issue).
Whilst this has been fixed in Workbox v5+, I am unable to upgrade due to another library in my build process requiring webpack v3 (Dynamic Importing in Laravel Mix)
The reason I mention the above is because unforunately the solution is not to upgrade to workbox v5+.
The Problem
I have an auto-generated file that looks like this:
self.__precacheManifest = (self.__precacheManifest || []).concat([
{
"revision": "68cd3870a6400d76a16c",
"url": "//css/app.css"
},
// etc...
]);
I need to somehow extract the the contents of the object stored within self.__precacheManifest, apply my own transformations, and then save it back to the file.
What I have Tried...
This is as far as I have got:
// As the precached filename is hashed, we need to read the
// directory in order to find the filename. Assuming there
// are no other files called `precache-manifest`, we can assume
// it is the first value in the filtered array. There is no
// need to test if [0] has a value because if it doesn't
// this needs to throw an error
let manifest = fs
.readdirSync(path.normalize(`${__dirname}/dist/js`))
.filter(filename => filename.startsWith('precache-manifest'))[0];
require('./dist/js/' + manifest);
// This does not fire because of thrown error...
console.log(self.__precacheManifest);
This throws the following error:
self is not defined
I understand why it is throwing the error, but I have no idea how I am going to get around this because I need to somehow read the contents of the file in order to extract the object. Can anyone advise me here?
Bear in mind that once I have applied the transformations to the object, I then need to save the updated object to the file...
Since self refers to window and window does not exist in node.js a way around is needed.
One thing that should work is to define the variable self in Node's global scope and let the require statement populate the content of the variable, like this:
global['self'] = {};
require('./dist/js/' + manifest);
console.log(self.__precacheManifest);
To save the modified contents back to the file
const newPrecacheManifest = JSON.stringify(updatedArray);
fs.writeFileSync('./dist/js/' + manifest, `self.__precacheManifest = (self.__precacheManifest || []).concat(${newPrecachedManifes});`, 'utf8');
I am trying to create an extension for visual studio code, which requires the ability to annotate lines in a file similar to the references shown in the image, linked below.
I want to be able to add an annotation, such as the one shown in the red rectangle, without modifying the source code file. I would like to be able to do so for every line of the source file. I also want to be able to make dynamic modifications to the annotations' contents.
I have searched VSC's documentation as well as elsewhere. I have not found it. Can anyone guide me in the right direction please?
I know the following is incorrect, but I don't know where else to check for how it should be accomplished.
class TestCodeLensProvider implements vscode.CodeLensProvider {
public provideCodeLenses(document: TextDocument, token: CancellationToken):
CodeLens[] | Thenable<CodeLens[]> {
return new Array<CodeLens>();
}
public resolveCodeLens?(codeLens: CodeLens, token: CancellationToken):
CodeLens | Thenable<CodeLens> {
return new CodeLens(new vscode.Range(new vscode.Position(1, 1), new vscode.Position(1, 2)),/*I also don't know how to specify my command here*/ );
}
}
export function activate(ctx: vscode.ExtensionContext): void {
ctx.subscriptions.push(
vscode.languages.registerCodeLensProvider(
'json', new TestCodeLensProvider()));
The feature in your screenshot is called "Code Lens". More specifcally, you're looking for the registerCodeLensProvider() function of the languages namespace. Or if you're writing a Language Server instead of using the VSCode API directly, the textDocument/codeLens request method.
https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers
How do I get a list of all the properties of GlobalEventHandlers?
Specifically, I want to test if a passed string is a property of GlobalEventHandlers, something like:
console.log(GlobalEventHandlers.includes('onClick')); // true
console.log(GlobalEventHandlers.includes('fizzBuzz')); // false
The only real way to get all of them is to build the list yourself, but you can loop over the keys in the window object and look for keys that start with on
Object.keys(window).filter(k => !k.indexOf('on'))
BUT that is not going to return just the built in ones. If someone set a custom event listener like
window.onfoobar = function () {}
than that will also show up in the result.
I wrote an npm package that does that for you.
Full usage and installation: global-event-handlers-map.
it extracts every global event handler under every object that exists under window (including window).
for example, by calling:
const getGlobalEventsHandlersMap = require('global-event-handlers-map');
const gehsMap = getGlobalEventsHandlersMap('WebSocket');
you will get the following result (gehsMap would be):
{
"WebSocket": [
"onopen",
"onerror",
"onclose",
"onmessage"
]
}
by calling getGlobalEventsHandlersMap() with no arguments, you will receive ALL global event handlers.
the README file should be very indicative and should help you understand how to get everything you need from that package.
you can either:
execute the code once in the browser, get the results, and use that map statically in your code.
integrate the library in your code and by that dynamically create the map every time your code runs in the browser.
the best way depends on your needs, and should be your call. i can help you understand which way is best for you depends on your needs.
hope that helps!
I am trying to listen for changes to settings in firefox's about:config that the user could have changed while my addon is running. The settings in question are part of the browser and not created by my addon.
I can read and set them manually when the user has used my addon with no problems using the "preferences/service" module, but I want to be able to make the appropriate changes in my addon if the user has changed a setting in about config independently of my addon.
The "simple-prefs" module provides a listener but that is only for settings specific to your application, like "extension.myaddon.mypreference" where as the settings I need to watch are like "network.someoptionhere"
If someone could point me in the right direction as to how I would go about this I would greatly appreciate it.
You'll need to use some XPCOM, namely nsIPrefService/nsIPrefBranch (e.g. via Services.jsm). This is the same stuff that preferences/service and simple-prefs wraps.
Here is a full example:
const {Ci, Cu} = require("chrome");
const {Services} = Cu.import("resource://gre/modules/Services.jsm", {});
function observe(subject, topic, data) {
// instanceof actually also "casts" subject
if (!(subject instanceof Ci.nsIPrefBranch)) {
return;
}
console.error(subject.root, "has a value of", subject.getIntPref(""), "now");
}
var branch = Services.prefs.getBranch("network.http.max-connections")
branch.addObserver("", observe, false);
exports.onUnload = function() {
// Need to remove our observer again! This isn't automatic and will leak
// otherwise.
branch.removeObserver("", observe);
};