ESLint/Prettier rule to disallow template literals without placeholders - eslint

Is there an ESLint or Prettier rule that would disallow template literals without a placeholder? I would like to replace backticks in template literals without placeholder with standard quotation marks '';
Allowed
const templateLiteral = `Some ${string}`;
Disallowed
const templateLiteral = `Some string`;
Turned into
const templateLiteral = 'Some string';

The quotes eslint rule helps you enforce single quotes. Add the following to your .eslintrc:
"rules": {
"quotes": ["error", "single", { "avoidEscape": true }]
}
You can verify that backticks/template literals without any expressions/substitutions are disallowed in the rule test code.

Related

ESLint rule to detect nested assignments

There seems to be no ESLint rule to detect nested variable assignments. This is a very common mistake.
function assert (cond) {
if (!cond) {
throw new Error("Assertion failed.");
}
}
function test () {
let var1 = 1;
assert(var1 = 2); // mistake: assigns 2 to var1!
console.log(var1);
}
I tried to propose a new rule at GitHub, but this is only possible when there is a related new ECMAScript feature. And I can't find an existing rule that could be extended accordingly. The no-cond-assign and no-return-assign rules are similar, but they would not be suitable for such an extension.
My question has been answered on GitHub by DMartens and mdjermanovic.
The no-restricted-syntax rule can be used:
e.g.:
"no-restricted-syntax": ["error", {
selector:
"AssignmentExpression:not(
ExpressionStatement > AssignmentExpression,
ForStatement > AssignmentExpression.update )",
message: "Do not nest assignments"
}],
or
"no-restricted-syntax": ["error", {
selector: ":not(ExpressionStatement, ForStatement) > AssignmentExpression",
message: "Do not nest assignments"
}],

How can I replace text from a config.json file automatically by a variable in node js

Hi and thank you for your help
I have a config.json file that contains this:
{
"test": {
"hi": {
"text": "Hi ${user.name}"
}
}
}
and I have index.js file that contains:
var config = require('./config.json')
var user = {name: "Test", tag: "#1234")
console.log(`${config.test.hi.text}`) // Output: "Hi ${user.name}"
// Expected output: Hi Test
I want when you change in the config.json the user.name to something like user.tag its automatically replaces him without .replace() function
thank you for your help :D
When using Template literals, the expressions in the placeholders and the text between the backticks (` `) get passed to a function that concatenates the strings into a single string, replacing the values inside $(variable).
This process happens at the time you define the template and cannot be resolved later as you do in your code. Refer to the documentation: Template literals
It would be also a bad coding practise as if the user variable didn't exist in the index.js file it wouldn't give you a compile error, but a nasty runtime error.
The only way to do it is to have your template literal in reach of your variable scope, that means that the template literal can read the variable at the moment it's executed. If you want to have the user instance and the template in different files, you can use a callback function as this:
config.js
const callback = (user) => {
return `Hi ${user.name}`
}
const config = {
callback,
anotherConfig: {
hi: {
example: "This is another config"
}
}
}
export default config;
index.js
import config from './config.js';
const user = {name: "Test", tag: "#1234"};
console.log(config.callback(user))
Output
Hi Test

Treating idents as string in Rust macros

I have a configuration struct with some top level properties which I would like to put in sections. I order to provide deprecation warnings I made the following macro
macro_rules! deprecated {
($config:expr, $old:ident, $section:ident, $new:ident) => {
if $config.$old.is_some() {
println!(
"$old configuration option is deprecated. Rename it to $new and put it under the section [$section]",
);
&$config.$old
} else {
if let Some(section) = &$config.$section {
&section.$new
} else {
&None
}
}
};
}
This doesn't seem to work as expected as the macro parameters aren't substituted inside a string. How can I change the macro to achieve the desired effect?
The stringify! macro can turn an element into a string literal, and the concat! macro can concatenate several literals into a single string literal:
println!(
concat!(
stringify!($old),
" configuration option is deprecated. Rename it to ",
stringify!($new),
" and put it under the section [",
stringify!($section),
"]",
)
);
Permalink to the playground

Enforce space before curly brace in functions

How do I enforce having a space before a curly brace in function declarations and expressions?
E.g.
var badFunc = function (){
};
function badFunc(){
}
var goodFunc = function () {
};
function goodFunc() {
}
I found https://github.com/eslint/eslint/issues/1618 but doesn't answer anything.
#Unidan I believe you are looking for space-before-blocks : 2 or however you want to set it
This is the rule you want to use: http://eslint.org/docs/rules/space-before-function-paren
/* eslint space-before-function-paren: [2, { "anonymous": "always", "named": "always" }]*/

Internet Explorer truncating flashVars containing JSON

This only happens in IE.
I'm using swfobject and loading the flash vars as such
var flashVars = {
myVar:'{"url":"http://google.com/", "id":"9999"}',
};
var params = {
allowFullScreen:"true",
wmode:"transparent",
allowScriptAccess:'always'
};
swfobject.embedSWF("mySwf.swf", "mySwf", "512", "318", "10.0.0", "./js/swfobject/expressInstall.swf", flashVars, params);
Everything works perfectly in all browser but IE. I checked myVar and it comes into the swf as { and that's it. I know it's dying at the '. I've tried putting a \ infront, then tried \\ and kept adding one slash until I got to \\\\\\\\. I even inverted all the slashes and tried the same ritual. Nothing.
I can get the string to finally come through, with inverted quotes and using double slashes, but then my JSON parser gets mad about there being slashes in my string.
Here's an example of what works, but of what is invalid JSON:
"{\\'url\\':\\'http://google.com/\\', \\'id\\':\\'9999\\'}"
Yep IE treats flashVars differently to all the other major browsers, I believe you need to make use of the JavaScript encodeURIComponent method which will escape all reserved characters from your String, eg:
// Removing all reserved characters from the flashVar value.
var flashVars = {
myVar: encodeURIComponent('{"url":"http://google.com/", "id":"9999"}'),
};
If you are passing multiple values in the flashVars then you could iterate through them and encode all chars in a single pass:
var flashVars = {
myVar: '{"url":"http://google.com/", "id":"9999"}',
anotherVar: 42
};
// Escape all values contained in the flashVars object.
for (key in flashVars) {
if (flashVars.hasOwnProperty(key)) {
flashVars[key] = encodeURIComponent(flashVars[key]);
}
}
As #dgmdan and #bcmoney suggested, it would probably make your code easier to read if you made use of JSON.stringify - however, you need to bear in mind that IE8 and below do not have a native JSON object, so you will need to include Crockford's JS Library in your HTML page.
// Making use of a JSON library.
var flashVars = {
myVar: encodeURIComponent(JSON.stringify({ url: "http://google.com/", id: "9999"})),
};
Also, it's worth bearing in mind that flashVars are limited to ~64k; so if you are planning to pass a lot of data, it might be better to use an ExternalInterface call to pull them from the JavaScript instead.
Try this to replace your first 3 lines:
var subVars = { url: "http://google.com/", id: "9999" };
var flashVars = { myVar: JSON.stringify(subVars) };

Resources