Stop babel parse and generate reformatting output code - javascript

I'm using #babel/parser to read in javascript, modify it and regenerate it with babel-generator. I need to do this while retaining the javascript's formatting but it's re-formatting it. I can't see anything else in the options for the parser or generator or docs that would stop it from doing this so I'm a bit lost. Here's what I have so far.
import { parse } from '#babel/parser';
import generate from 'babel-generator';
var file = parse(script, {
sourceType: 'module',
ranges: true,
tokens: true,
plugins: ['nullishCoalescingOperator', 'typescript']
});
var script = generate(file, {
retainLines: true,
comments: true
});
console.log(script.code);
The test script I am passing it is below;
import This from 'that'
import That from './this'
export default (() => {
return Object.assign(
{},
This
{
That
}
)
})()
However generate is returning the script below;
import This from 'that'
import That from './this'
export default (() => {
return Object.assign(
{},
This
{
That });
})();
As you can see it's changing the number of spaces in a return, collapsing the end }) of the Object.assign and adding semi-colons. It will be reading in script from lots of different formats and styles and I can't change it and ideally don't want to have to provide it with an es-lint file, is there anyway to get it to print the code back out with the exact same formatting?
EDIT: the ast nodes contain the loc and range vales but it seems to be ignoring it. I'm not even sure if it's parsing it incorrectly or if the generate is ignoring it.
"loc": {
"start": {
"line": 10,
"column": 8
},
"end": {
"line": 10,
"column": 10
}
},
"range": [
319,
321
],

you need use jscodeshift, instead of babel.This library is more suitable for this scenario.
https://github.com/facebook/jscodeshift

Related

#nuxtjs/i18n locales changing after refresh

I have an application where I try to put the language management but I face a difficulty.
I'm on the latest version of #nuxtjs/i18n. When I change language, my URl changes, my labels change, everything is fine. When I refresh my page, however, the system reverts to the old language.
Here is my conf:
[
'#nuxtjs/i18n',
{
locales,
defaultLocale,
lazy: true,
langDir: 'locales/',
vueI18n: {
fallbackLocale: defaultLocale,
},
},
],
['~/.build/merge-and-compare-locales.js', { defaultLocale }],
export const locales = [
{
code: 'en',
file: 'en.json',
},
{
code: 'fr',
file: 'fr.json',
},
]
export const defaultLocale = 'fr'
What more do I need to do to make it keep the language before refresh?
I specify that I use this method to change the language:
changeLocale(code: string) {
this.$i18n.setLocale(code)
},
Locally it works fine. On the other hand on any other environment it does not work, the refresh makes return to the default language
i have same problem and it's come from ssr...
inside your store/index you should have a nsi (nuxt server init) function
something like this.
/** initial the store when user fetch the web app */
async nuxtServerInit(ssrContext: Context) {
if (this.$i18n.locale==='ar') {
ssrContext.redirect("/ar");
}
else if (this.$i18n.locale === 'fa')
{
ssrContext.redirect('/')
}
}

xml2js valueProcessor removing \t and \n

I have a problem with parsing an XML file.
I want to remove strings with characters like \t\n.
XML File: http://ftp.thinkimmo.com/home/immoanzeigen24/immo.xml
{
trim: true,
normalize: true,
attrValueProcessors: [cleanValue, name => name],
valueProcessors: [cleanValue, name => name]
}
cleanValue:
const cleanValue = value => {
return value.toString().trim().replace("\t","atest");
};
I tried cleaning it with a lot of regex I've found online - but value always stays like following:
"verwaltung_objekt": {
"objektadresse_freigeben": "0",
"verfuegbar_ab": "nachaasjkdhkjshadjkashdAbsprache",
"bisdatum": "2016-01-15",
"min_mietdauer": "\n\t\t\t\t",
"max_mietdauer": "\n\t\t\t\t",
}
This is a difficult one!
I'd suggest following a simple strategy and pre-processing the xml data before you parse it.
This should resolve your issue at least.
If you just do something like:
function trimXml(xml) {
return xml.replace(/>\s+</g, "><");
}
xml = trimXml(xml);
Then parse the trimmed xml data. You should see the output now looks like so:
"verwaltung_objekt": [
{
"objektadresse_freigeben": [
"1"
],
"abdatum": [
"2017-03-01"
],
"min_mietdauer": [
""
],
"max_mietdauer": [
""
]
}
],
Which is a bit more like what you want!

How do I format JSON code in Monaco Editor with API?

I am working with monaco editor aka the VS Code engine in a web project.
I am using it to allow users to edit some JSON that has a JSON Schema set, to help give some auto-completion.
When they save their changes and wish to re-edit their work, the JSON that I load back into the editor is converted to a string but this renders the code out on a single line and I would much prefer the JSON to be prettier as if the user right clicks and uses the Format Document command from the context menu or keyboard shortcut etc..
So this
{ "enable": true, "description": "Something" }
Would become this
{
"enable": true,
"description:" "Something"
}
Current attempt
I have tried the following but it feels very hacky to use a timeout to wait/guess when the content has loaded
require(['vs/editor/editor.main'], function() {
// JSON object we want to edit
const jsonCode = [{
"enabled": true,
"description": "something"
}];
const modelUri = monaco.Uri.parse("json://grid/settings.json");
const jsonModel = monaco.editor.createModel(JSON.stringify(jsonCode), "json", modelUri);
const editor = monaco.editor.create(document.getElementById('container'), {
model: jsonModel
});
// TODO: YUK see if we can remove timeout, as waiting for the model/content to be set is weird
// Must be some nice native event?!
// ALSO ITS SUPER JARRING WITH FLASH OF CHANGE
setTimeout(function() {
editor.getAction('editor.action.formatDocument').run();
}, 100);
});
<script src="https://cdn.jsdelivr.net/npm/monaco-editor#0.19.3/min/vs/loader.js"></script>
<script>
require.config({
paths: {
'vs': 'https://cdn.jsdelivr.net/npm/monaco-editor#0.19.3/min/vs'
}
});
</script>
<div id="container" style="width:800px;height:600px;border:1px solid grey"></div>
Does anyone have a better idea or solution to this please?
require(['vs/editor/editor.main'], function() {
// JSON object we want to edit
const jsonCode = [{
"enabled": true,
"description": "something"
}];
const modelUri = monaco.Uri.parse("json://grid/settings.json");
const jsonModel = monaco.editor.createModel(JSON.stringify(jsonCode, null, '\t'), "json", modelUri);
const editor = monaco.editor.create(document.getElementById('container'), {
model: jsonModel
});
});
<script src="https://cdn.jsdelivr.net/npm/monaco-editor#0.19.3/min/vs/loader.js"></script>
<script>
require.config({
paths: {
'vs': 'https://cdn.jsdelivr.net/npm/monaco-editor#0.19.3/min/vs'
}
});
</script>
<div id="container" style="width:800px;height:600px;border:1px solid grey"></div>
Thanks to https://stackoverflow.com/users/1378051/dalie for reminding me about the extra arguments to JSON.stringify
Answer
Use the tab character for the space argument
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
const jsonModel = monaco.editor.createModel(JSON.stringify(jsonCode, null, '\t'), "json", modelUri);
I use this function to tidy my code:
tidy() {
this.monacoEditor.trigger('anyString', 'editor.action.formatDocument')
}
where monacoEditor is result of this.monacoEditor = monaco.editor.create(this.$el, { ...this.editorOptions })

Mixing custom function with predefined ones in reductio for crossfilter

I am trying to use both the .std() and the .custom() function in the reductio library.
My code is as follows for the reductio part:
dims.theme1 = myCrossfilter.dimension(function(d) {return(d.theme1);});
groups.theme1 = dims.theme1.group();
var reducer = reductio()
.custom({initial:reduceInit,add:reduceAdd,remove:reduceRemove})
.std("pl");
reducer(groups.theme1);
My code for the custom functions is :
reduceAdd = function(p,v) {
if (!p.fundsData.hasOwnProperty(v.AdyneAccount)) {
p.fundsData[v.AdyneAccount]=0;
}
if (!p.stratsData.hasOwnProperty(v.Strategy)) {
p.stratsData[v.Strategy]=0;
}
p.fundsData[v.AdyneAccount]+=+v.plfund;
p.stratsData[v.Strategy]+=+v.plstrat;
p.value+=+v.pl;
return(p);
};
reduceRemove = function(p,v) {
p.fundsData[v.AdyneAccount]-=+v.plfund;
p.stratsData[v.Strategy]-=+v.plstrat;
p.value-=+v.pl;
return(p);
};
reduceInit = function(p,v) {
return({
value:0,
fundsData:{},
stratsData:{}
});
};
I would expect my result (by doing groups.theme1.all()[0]) to look like the below (the values I have put in are random for this example) :
{
"key": "theTheme",
"value": {
"value": 10,
"fundsData": {
"a": 10,
"b": 5,
"c": 4
},
"stratsData": {
"somename": 8
},
"count": null,
"sum": null,
"sumOfSq": null,
"std": 0
}
}
And it does but it doesn't produce the values for count, sum and sumOfSq (so for std neither of course).
When I run .std("pl") by itself without my custom function on the exact same set of records, it works as expected. I do not understand why the addition of a custom function would prevent the correct calculation for the .std("pl") part.
All help welcome !
It looks to me like this is a bug in Reductio. The test names indicate that this shouldn't interfere with other aspects of reducers, but the content of the test makes clear that it does wipe them out.
https://github.com/crossfilter/reductio/blob/cd99f5043990a838b7e04ea86dbae3c1a1203119/test/custom.spec.js#L48
I've created an issue for this. No idea when I'll be able to get to it though. You'll probably want to just implement a normal Crossfilter custom reducer for this until I can fix it or someone sends a pull request.

How do you use require() within a map function?

Looking at the docs for CouchDB 1.6.1 here, there is mention that you can use the JS require(path) function. How do you do this? The documentation says path is "A CommonJS module path started from design document root".
My design doc is called _design/data. I have uploaded an attachment to this design doc called test.js, which can be accessed at /_design/data/test.js, and contains the following code:
exports.stuff = function() {
this.getMsg = (function() {
return 'hi';
})()
}
But the following code in my map function:
function(doc) {
try {
var x = require('test.js');
} catch (e) {
emit ('error', e)
}
}
results in this error:
["error", "invalid_require_path", "Object has no property \"test.js\". {\"views\":{\"lib\":null},\"_module_cache\":{}}"]
It looks like require is looking for the path as an object in the docparam... but I don't understand why if it is.
Looking at this link, describing this feature in an older version of CouchDB, it says you can:
However, in the upcoming CouchDB 1.1.x views will be able to require modules provided they exist below the 'views' property (eg, 'views/lib/module')
And gives the following code example:
{
"_id": "_design/example",
"lib": {
// modules here would not be accessible from view functions
},
"views": {
"lib" {
// this module is accessible from view functions
"module": "exports.test = 'asdf';"
},
"commonjs": {
"map": function (doc) {
var val = require('views/lib/module').test;
emit(doc._id, val);
}
}
}
}
But this did not work for me on CouchDB 1.6.1. I get the error:
{message: "mod.current is null", fileName: "/usr/share/couchdb/server/main.js", lineNumber: 1137, stack: "([object Array],[object Object])#/usr/share/couchdb/server/main.js:1137\n([object Array],[object Object])#/usr/share/couchdb/server/main.js:1143\n([object Array],[object Object],[object Object])#/usr/share/couchdb/server/main.js:1143\n(\"views/lib/module\")#/usr/share/couchdb/server/main.js:1173\n([object Object])#undefined:3\n([object Object])#/usr/share/couchdb/server/main.js:1394\n()#/usr/share/couchdb/server/main.js:1562\n#/usr/share/couchdb/server/main.js:1573\n"
In your question you didn't provide the function as a string. It's not too easy to spot, but you must stringify functions before storing them in CouchDB (manually or by using .toString()). Caolan has that error in the post that you linked.
Using this example:
15 views: {
16 lib: {
17 foo: "exports.bar = 42;"
18 },
19 test: {
20 map: "function(doc) { emit(doc._id, require('views/lib/foo').bar); }"
21 }
22 }
Found in older CouchDB docs here: https://wiki.apache.org/couchdb/CommonJS_Modules
I got an example working. Not sure what the difference was really... I was running 'temp' views instead of saving but I don't know why that would have effected the require statement

Categories

Resources