undefined d3.scale in Typescript - d3.js

I'm new with Typescript (2 weeks), and I work on project to wrap the d3.js framework.
I'm encountered a problem with the usage of "d3.d.ts", namespace, export module, import.
My problem : When I try to use the d3.scale.linear(), I have the error in my browser console :
TypeError: d3.scale is undefined
The code :
/// <reference path="../typings/d3.d.ts">;
"use strict";
var linear = d3.scale.linear();
console.log("linear resolv !")
My compiler option (I've no error on the compilation process, but perhaps it's interesting) :
{
"files": [
"src/twod3/workspace.ts",
"src/twod3/component/basic.ts",
"src/twod3/component/data.ts",
"src/twod3/component/operation.ts",
"src/main.ts"
],
"compilerOptions": {
"noImplicitAny": true,
"target": "es2015",
"module":"commonjs",
"sourceMap":true
}
}
I try different import strategy without success.
The d3.d.ts
declare namespace d3 {
...
export module scale {
...
export function linear(): Linear<number, number>;
...
}
}
I don't understand the problem, thank you for your help.

Be careful of the version for d3.js
In version 4.2.1 d3.scale.linear(); gives the following error.
TypeError: d3.scale.linear() scale is undefined
I fixed this error in version 4.2.1 by using d3.scaleLinear();

I had a similar kind of issue. I had to match the D3 version, that supported the in built methods for d3.
Either match the version of the D3.js, make sure you update your browser or match the in built methods for your current version.
My supported version for d3.scale.ordinal is '3.5.17', previously I was at the latest version.

Related

GraphQL Nexus Schema (nexusjs) doesn't compile with scalar types

I am trying to follow the documentation on the Nexus-Schema (nexusjs) website for adding scalar types to my GraphQL application.
I have tried adding many of the different implementations to my src/types/Types.ts file using the samples provided in the documentation and the interactive examples. My attempts include:
Without a 3rd party libraries:
const DateScalar = scalarType({
name: 'Date',
asNexusMethod: 'date',
description: 'Date custom scalar type',
parseValue(value) {
return new Date(value)
},
serialize(value) {
return value.getTime()
},
parseLiteral(ast) {
if (ast.kind === Kind.INT) {
return new Date(ast.value)
}
return null
},
})
With graphql-iso-date 3rd party library:
import { GraphQLDate } from 'graphql-iso-date'
export const DateTime = GraphQLDate
With graphql-scalars 3rd party library (as shown in the ghost example):
export const GQLDate = decorateType(GraphQLDate, {
rootTyping: 'Date',
asNexusMethod: 'date',
})
I am using this new scalar type in an object definition like the following:
const SomeObject = objectType({
name: 'SomeObject',
definition(t) {
t.date('createdAt') // t.date() is supposed to be available because of `asNexusMethod`
},
})
In all cases, these types are exported from the types file and imported into the makeSchema's types property.
import * as types from './types/Types'
console.log("Found types", types)
export const apollo = new ApolloServer({
schema: makeSchema({
types,
...
context:()=>(
...
})
})
The console.log statement above does show that consts declared in the types file are in scope:
Found types {
GQLDate: Date,
...
}
If I run the app in development mode, everything boots up and runs fine.
ts-node-dev --transpile-only ./src/app.ts
However, I encounter errors whenever I try to compile the app to deploy to a server
ts-node ./src/app.ts && tsc
Note: This error occurs occurs running just ts-node ./src/app.ts before it gets to tsc
The errors that shown during the build process are the following:
/Users/user/checkouts/project/node_modules/ts-node/src/index.ts:500
return new TSError(diagnosticText, diagnosticCodes)
^
TSError: тип Unable to compile TypeScript:
src/types/SomeObject.ts:11:7 - error TS2339: Property 'date' does not exist on type 'ObjectDefinitionBlock<"SomeObject">'.
11 t.date('createdAt')
Does anyone have any ideas on either:
a) How can I work around this error? While long-term solutions are ideal, temporary solutions would also be appreciated.
b) Any steps I could follow to debug this error? Or ideas on how get additional information to assist with debugging?
Any assistance would be very much welcomed. Thanks!
The issue seems to be resolved when --transpile-only flag is added to the nexus:reflect command.
This means the reflection command gets updated to:
ts-node --transpile-only ./src/app.ts
and the build comand gets updated to:
env-cmd -f ./config/.env ts-node --transpile-only ./src/app.ts --nexusTypegen && tsc
A github issue has also been created which can be reviewed here: https://github.com/graphql-nexus/schema/issues/690

How to resolve the Vuetify error "installComponents has already been declared"?

Nuxt.js latest version throws the following error while building or deploying the project that has Vuetify.
remote: > import installComponents from "!../node_modules/vuetify-loader/lib/runtime/installComponents.js"
Module parse failed: Identifier 'installComponents' has already been declared (53:7)
You may need an appropriate loader to handle this file type.
|
| /* vuetify-loader */
> import installComponents from "!../../../node_modules/vuetify-loader/lib/runtime/installComponents.js"
| import { VBtn } from 'vuetify/lib'
| import { VCard } from 'vuetify/lib'
It's hard to tell without a nuxt.config.js. But I had a problem like that. Earlier, I used a plugin to connect Vuetify. Then I installed the #nuxtjs/vuetify module, and the problem came up.
The problem is most likely related to treeShaking. #nuxtjs/vuetify turns on treeShaking only when the build happens. So you don't have a problem in dev mode, but there are problems with the build.
In my case the reason was that I forgot to remove VuetifyLoaderPlugin from the build section in nuxt.config.js.
transpile: ['vuetify/lib'],
plugins: [new VuetifyLoaderPlugin()],
Also I recommend enable treeShaking for the dev mode too. This will allow to use SASS variables in dev-mode. From #nuxtjs/vuetify version 2 it will always be enabled.
vuetify: {
customVariables: ['~/assets/variables.scss'], // need treeShake
treeShake: true,
},
Please remove buildModules inside nuxt.config.js, this is for those who are using Nuxt.js
{
buildModules: [
// Simple usage
'#nuxtjs/vuetify',
// With options
['#nuxtjs/vuetify', { /* module options */ }]
]
}
Add modules this one is for latest version
modules: [
'#nuxtjs/vuetify',
],
vuetify: {
//what ever options you may like
},

How to use functions in grunt-sass?

My current project uses grunt-sass to translate scss files into css.
According to the grunt-sass documentation, I can use any option that node-sass provides except for a few:
Options
See the node-sass options, except for file, outFile, success, error.
My project compiles two CSS files out of one SCSS file. The SCSS file has if-statements in it that provides different code depending on the value of the version variable ($bootstrap-version: 3; or $bootstrap-version: 4;).
I would like to use the node-sass option functions to return the bootstrap version to my SCSS files.
Here's my gruntfile. The functions: {...} path is how I would have expected the option to work.
// Compile Sass
sass: {
bootstrap3: {
options: {
style: 'expanded'
functions: {getBootstrapVersion: function(){return 3;}}
},
files: {
'dist/bootstrap3/css/my-bs3-variation.css': './bootstrap3/scss/my-bs3-variation.scss'
},
},
bootstrap4: {
options: {
style: 'expanded',
functions: {getBootstrapVersion: function(){return 4;}}
},
files: {
'dist/bootstrap4/css/my-bs4-variation.css': './bootstrap4/scss/my-bs4-variation.scss'
}
}
In the SCSS file, I call the function like this:
$bootstrap-version: getBootstrapVersion();
h1:before {
content: "Bootstrap " + $bootstrap-version + " Version of ";
}
However, when trying to compile it, I get the errir >> Error: error in C function getBootstrapVersion: A SassValue object was expected. for the line where I call the function.
The example in the node-sass documentation does not help me much. What did I do wrongly? Or are there any better examples out there that I just did not find?
I use grunt-sass version 2.0.0 and node-sass version 4.7.2
The functions must return a SassValue object.
Unfortunately, I don't believe it is possible to do that with grunt-sass alone because we need to wrap your returned numbers 4 and 3 in typing functions defined in node-sass (which grunt-sass does not expose...).
For example, with node-sass in javascript, one may use something like sass.types.Number(4) to declare 4 as a Number SassValue.
Here, sass is the node-sass import const sass = require('node-sass');, which is not available in grunt...

Loading D3 with Nuxt/Vue

I am trying to implement D3 in an app I am building with Nuxt. I have successfully imported it into a view in the <script> section with import * as d3 from 'd3' however because the app is being rendered server-side D3's functionality doesn't work (i.e. d3.select(...)) due to the lack of browser. In the Nuxt plugin documentation it suggests a pattern for client-only external plugins:
module.exports = {
plugins: [
{ src: '~plugins/vue-notifications', ssr: false }
]
}
I attempted to implement the pattern in the nuxt.config.js of my project:
module.exports = {
head: {
title: 'My Demo App',
meta: [...],
link: [...]
},
loading: {...},
plugins: [
{ src: '~node_modules/d3/build/d3.js', ssr: false}
]
}
However D3 throws a ReferenceError while looking for document and Nuxt throws a SyntaxError in the console pointing to something in the plugins field of nuxt.config.js.
For reference, demo.vue:
<template>
<div class="demo-container"></div>
</template>
<script>
import * as d3 from 'd3';
d3.select('.demo-container');
</script>
Would someone be able to point to what I'm doing wrong?
For anyone coming to this page looking for a solution,
these suggestions from piyushchauhan2011 here on GitHub sent me in the right direction.
All I needed to do:
import d3 in my single-file component, and then
do any DOM manipulation with d3 only within mounted()
Before all this, I had to of course add d3 to my project with yarn add d3 (or npm install d3).
[Edit: removed link that no longer works. It wasn't that relevant anyway.]
I was getting an error:
Must use import to load ES Module: .../node_modules/d3/src/index.js require() of ES modules is not supported. require() of .../node_modules/d3/src/index.js from .../node_modules/vue-server-renderer/build.dev.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules. Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from .../node_modules/d3/package.json.
I solved it by reading this: https://github.com/nuxt/nuxt.js/issues/9223
which indicates you can add this to your nuxt.config.js file:
build: {
standalone: true,
}
This allowed the d3 import to work.
import * as d3 from "d3";
Here's a simple step-by-step tutorial:
Create a new NuxtJS project (Skip this step if you have an existing project)
npm init nuxt-app nuxtjs-d3js-example
Install D3JS
npm install d3
npm install #types/d3 --save-dev
Import D3JS and add a target
HTML:
<p id="d3-target"></p>
JavaScript:
import * as d3 from 'd3'
export default {
name: 'NuxtTutorial',
mounted: function() {
d3.select("#d3-target").text("This text is manipulated by d3.js")
},
}
Fix ES Module error (mentioned by #agm1984)
Error:
require() of ES Module /home/johnson/projects/nuxtjs-d3js-example/nuxtjs-d3js-example/node_modules/d3/src/index.js from /home/johnson/projects/nuxtjs-d3js-example/nuxtjs-d3js-example/node_modules/vue-server-renderer/build.dev.js not supported. Instead change the require of index.js in /home/johnson/projects/nuxtjs-d3js-example/nuxtjs-d3js-example/node_modules/vue-server-renderer/build.dev.js to a dynamic import() which is available in all CommonJS modules.
nuxt.config.js:
build: {
standalone: true,
}
A minimal project example can be found at: https://github.com/j3soon/nuxtjs-d3js-example, with each step detailed in the Git commit history.

Find a good way to get a coverage report on ES6 code

Here is my problem : in an AngularJS project, I use Babel 6 (ES2015 + stage3 + decorators), SystemJS and Karma + Jasmine.
All is OK, except for code coverage : I can't find a good way to get a coverage report on ES6 code instead of transpiled ES5.
I have some restrictions :
no Github npm dependencies
no deprecated projects (like isparta)
should run on Windows (yeah, I know, but I have to) and GNU/Linux
This question is especially oriented to a local html coverage report, but I also need a format that could be used in SonarQube.
There seems to be a huge lake of support on this question (especially with Decorators and SystemJS), so, along with some issues on Github, maybe the stackoverflow community could share a way to do this.
If you need some extras, you can see this project on Github (Sedona-Solutions/sdn-angularjs-seed), and look at the related issues (Sedona-Solutions/sdn-angularjs-seed#5) with references to all related issues and projects I could found.
About remap-istanbul
Here is my transpilation and mapping gulp task :
gulp.task('es6', function () {
return gulp.src(paths.source, { base: 'app' })
.pipe(plumber())
.pipe(changed(paths.output, { extension: '.js' }))
.pipe(sourcemaps.init())
.pipe(babel(compilerOptions))
.pipe(ngAnnotate({
sourceMap: true,
gulpWarnings: false
}))
.pipe(sourcemaps.write("."))
.pipe(gulp.dest(paths.output))
});
Karma-coverage
coverageReporter: {
reporters: [
{
type: 'json',
dir: 'target/coverage/',
subdir: '.',
file: 'coverage-final.json'
}
]
}
and the test:remap gulp task :
gulp.task('test:remap', ['test'], function (done) {
return gulp.src(paths.coverage + '/coverage-final.json')
.pipe(remapIstanbul({
reports: {
'json': paths.coverage + '/coverage.json',
'html': paths.coverage + '/html-remaped/'
},
fail: true,
useAbsolutePaths: true
}));
});
due to the first remap-istanbul issue, I get the following error :
C:\...\sdn-angularjs-seed\node_modules\remap-istanbul\node_modules\istanbul\lib\report\html.js:288
text = structuredText[startLine].text;
^
TypeError: Cannot read property 'text' of undefined
at C:\...\sdn-angularjs-seed\node_modules\remap-istanbul\node_modules\istanbul\lib\report\html.js:288:53
You can see the corresponding code on github.
It could be an error on some mapping generation, or paths ... If you think so, tell me.
karma-coverage + remap-istanbul should work fine

Resources