Ignore "cannot find module" error on typescript - import

Can the Typescript compiler ignore the cannot find module 'x' error on import expressions such as:
//How to tell the compiler that this module does exists
import sql = require('sql');
There are multiple npm libraries such as node sql that doesn't have existing typings
Is there a way to tell the compiler to ignore this error other than creating a new definition file with the declare module x ... ?

As of TypeScript 2.6 (released on Oct 31, 2017), now there is a way to ignore all errors from a specific line using // #ts-ignore comments before the target line.
The mendtioned documentation is succinct enough, but to recap:
// #ts-ignore
const s : string = false
disables error reporting for this line.
However, this should only be used as a last resort when fixing the error or using hacks like (x as any) is much more trouble than losing all type checking for a line.
As for specifying certain errors, the current (mid-2018) state is discussed here, in Design Meeting Notes (2/16/2018) and further comments, which is basically
"no conclusion yet"
and strong opposition to introducing this fine tuning.

If you just want to bypass the compiler, you can create a .d.ts file for that module, for instance, you could create a sql.d.ts file and inside have this:
declare module "sql" {
let _sql: any;
export = _sql;
}

Solved This
By default #ts-check looks for definitions of a module, either its your own code or external libraries.
Since we are not using ES6 style modules, then we must we are using
commonjs, check my jsconfig.json file for help.
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"lib": ["es5", "es6", "es7"]
},
"include": ["src/**/*"],
"exclude": ["node_modules"],
"typeAcquisition": { "enable": true }
}

Related

How to fix vscode GnuCOBOL setup "configuration error: default.conf: No such file or directory"

we are using cobol now, but this config error keeps on appearing and I do not know how to fix this thing. Any help would really mean alot. (Just a beginner and trying to learn vscode)
Late, but perhaps worth it. Currently there is a cobenv.bat or .sh (if you are on linux). The whole path to the file may differ for me is this:
C:\msys64\mingw64\bin\cobenv.cmd
You'll notice that if you execute the file and run the compiler everything works fine, but once you close that bash the error shows up again.
That's because the scope of those variables was just that session. You may execute it every time you run the compiler or you can make those variables to persist on your system. In my case I did the later, modifying cobenv.cmd
But not those lines with the variable PATH.
So this lines, i.e., whenever we encounter this same three variables. For instance, after a certain if in that file we encounter:
setx "COB_LIBRARY_PATH" "%MINGW_ROOT_PATH%lib\gnucobol%COB_LIBRARY_PATH%"
setx "COB_COPY_DIR" "%MINGW_ROOT_PATH%share\gnucobol\copy"
setx "COB_CONFIG_DIR" "%MINGW_ROOT_PATH%share\gnucobol\config"
Default value: set.
New value: setx.
Delete the = to comply with the correct syntax. Check the compiler with different new session.
This message is only presented in vscode's Terminal after you've entered a command there, it is actually not related to vscode.
The "common" way with vscode would be to create a vscode task for the compilation and configure a problem matcher, too, so vscode is able to parse the messages. For details see vscode docs "Integrate with External Tools via Tasks".
As the message is coming from the GnuCOBOL compiler it may be reasonable to check in its discussion board, which also includes a note how to use your setup of vscode with GnuCOBOL MinGW package, this would be your starting point, assuming D:\COBOL is the place where you have your sources (and this is the alos the workspaceFolder as in your screenshot), D:\COBOL\copy where your copybook reside and D:\GnuCOBOL where the MinGW package is:
{
"version": "2.0.0",
"tasks": [
{
"label": "GnuCOBOL - cobc (compile single file)",
"type": "shell",
"command": "cobc",
"args": [
"-I${workspaceFolder}\\copy",
"${file}"
],
"problemMatcher": "$gnucobol3-cobc",
"options": {
"env": {
"COB_CFLAGS": "-I\"D:\\GnuCOBOL\\include\"",
"COB_CONFIG_DIR": "D:\\GnuCOBOL\\config",
"COB_COPY_DIR": "D:\\GnuCOBOL\\copy",
"COB_LDFLAGS": "-L\"D:\\GnuCOBOL\\lib\"",
"COB_LIBRARY_PATH": "D:\\GnuCOBOL\\extras",
"PATH": "D:\\GnuCOBOL\\bin:${env:PATH}"
}
},
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
Instead of directly calling cobc you could also call cobc.bat or similar, then create it with all your default options set there (or, if you use the official mingw packages, just call the set_env.cmd) then call the compiler.
Concerning "how to fix that message" - make sure you have the "config" directory of GnuCOBOL and have COB_CONFIG_DIR set to it either in the task definition or outside of vscode (for example by starting vscode from the "Developer prompt for GnuCOBOL MinGW" (which is the set_env.cmd distributed with it).

Need help to complete installation of linter-stylelint for Atom

I am really sorry for this newbie question but I can't see how solve that...
I installed linter-stylelint and tried to configure it like it's said there:
https://atom.io/packages/linter-stylelint
So:
- I placed a stylelint.config.js file in my project.
- In the settings, I checked Use standard
- But can't see what I have to do to "Add a stylelint section in your package.json"
On my Mac I see the file:
/Users/eric/node_modules/stylelint-config-standard
But I don't know what code do I have to insert inside...
By the way, when I try to use linter-stylelint in a css file I get the error message:
Unable to parse stylelint configuration
Unexpected token :
In my stylelint.config.js, I have the following code for now:
{
"extends": "stylelint-config-standard"
"rules" {
"no-unsupported-browser-features": [ true, { "severity": "warning" }]
}
}
Thanks if you can help me!
;)
Paul
So: - I placed a stylelint.config.js file in my project. - In the settings, I checked Use standard
According to the docs you reference, you should either place a stylelint.config.js file or check "Use standard".
I get the error message Unable to parse stylelint configuration Unexpected token :
This is because the JSON of your configuration file is invalid. It is missing both a comma and a colon. Use a service like JSONLint to validate JSON. Your fixed config is:
{
"extends": "stylelint-config-standard",
"rules": {
"no-unsupported-browser-features": [true, {
"severity": "warning"
}]
}
}
Even though this config is valid JSON, it won't work because the no-unsupported-browser-features rule is no longer built into stylelint. It is, however, available as a plugin. You'll need to follow the plugin's instructions if you wish to use it.
I am really sorry for this newbie question
It's fine. We are all newbies in the beginning! As you're just getting started with stylelint, I suggest you remove the stylelint.config.js file and ensure the "Use Standard" box is checked. This is likely the quickest way to get going. Once you are more comfortable with the tool, you can investigate creating your own configuration file for your specific needs.

how do you get flow to work with babel module-alias?

I am trying to get flow to type check my code but it is giving me an error when it can't find paths that have been rewritten using babel-plugin-module-alias.
I have unsuccessfully tried to use the resolve_dirname option in the flowconfig.
Can someone please tell me if it is possible to use this babel plugin with flow?
.babelrc
{
"plugins": [
"transform-flow-strip-types",
["module-alias", [
{ "src": "./app", "expose": "app" },
]]
]
}
.flowconfig
[options]
module.system.node.resolve_dirname=app
app/main.js
import bar from 'app/foo';
app/main.js:3
3: import bar from 'app/foo';
^^^^^^^^^^ app/foo. Required module not found
module.system.node.resolve_dirname actually tells Flow where to start resolving things from. If you want Flow to resolve starting from 'app', you need to point it one directory higher than app.
Alternatively, you can probably also use `module.name_mapper='^app/([a-z-A-Z0-9$_/]+)$' -> 'src/\1'
Here is how this can be achieved with module.name_mapper setting in .flowconfig [options]. Works in flow version 0.56.0
module.name_mapper='^app/\([-a-zA-Z0-9$_/]+\)$' -> '<PROJECT_ROOT>/src/\1'

How can I use my webpack's html-loader imports in Jest tests?

I am just getting started with the Jest test framework and while straight up unit tests work fine, I am having massive issues testing any component that in its module (ES module via babel+webpack) requires a HTML file.
Here is an example:
import './errorHandler.scss';
import template from './errorHandler.tmpl';
class ErrorHandler {
...
I am loading the component specific SCSS file which I have set in Jest's package.json config to return an empty object but when Jest tries to run the import template from './errorHandler.tmpl'; line it breaks saying:
/Users/jannis/Sites/my-app/src/scripts/errorHandler/errorHandler.tmpl.html:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){<div class="overlay--top">
^
SyntaxError: Unexpected token <
at transformAndBuildScript (node_modules/jest-runtime/build/transform.js:284:10)
My Jest config from package.json is as follows:
"jest": {
"setupTestFrameworkScriptFile": "<rootDir>/test/setupFile.js",
"moduleDirectories": ["node_modules"],
"moduleFileExtensions": ["js", "json", "html", "scss"],
"moduleNameMapper": {
"^.+\\.scss$": "<rootDir>/test/styleMock.js"
}
}
It seems that the webpack html-loader is not working correctly with Jest but I can't find any solution on how to fix this.
Does anyone know how I can make these html-loader imports work in my tests? They load my lodash template markup and i'd rather not have these at times massive HTML chunks in my .js file so i can omit the import template from x part.
PS: This is not a react project, just plain webpack, babel, es6.
I encountered this specific problem recently and creating your own transform preprocesser will solve it. This was my set up:
package.json
"jest": {
"moduleFileExtensions": [
"js",
"html"
],
"transform": {
"^.+\\.js$": "babel-jest",
"^.+\\.html$": "<rootDir>/test/utils/htmlLoader.js"
}
}
NOTE: babel-jest is normally included by default, but if you specify a custom transform preprocessor, you seem to have to include it manually.
test/utils/htmlLoader.js:
const htmlLoader = require('html-loader');
module.exports = {
process(src, filename, config, options) {
return htmlLoader(src);
}
}
A bit late to the party, but wanted to add that there is also this html-loader-jest npm package out there to do this if you wanted to go that route.
Once you npm install it you will add it to your jest configuration with
"transform": {
"^.+\\.js$": "babel-jest",
"^.+\\.html?$": "html-loader-jest"
}
For Jest > 28.x.x with html-loader:
Create a custom transformer as documented here.
jest/html-loader.js
const htmlLoader = require("html-loader");
module.exports = {
process(sourceText) {
return {
code: `module.exports = ${htmlLoader(sourceText)};`,
};
},
};
Add it to your jest config.
jest.config.js
...
// A map from regular expressions to paths to transformers
transform: {
"^.+\\.html$": "<rootDir>/jest/html-loader.js",
},
...
It will fix the error : Invalid return value: process() or/and processAsync() method of code transformer found at "<PATH>" should return an object or a Promise resolving to an object.
Maybe your own preprocessor file will be the solution:
ScriptPreprocessor
Custom-preprocessors
scriptpreprocessor: The path to a module that provides a synchronous function from pre-processing source files. For example, if you wanted to be able to use a new language feature in your modules or tests that isn't yet supported by node (like, for example, ES6 classes), you might plug in one of many transpilers that compile ES6 to ES5 here.
I created my own preprocessor when I had a problems with my tests after added transform-decorators-legacy to my webpack module loaders.
html-loader-jest doesn't work for me. My workaround for this:
"transform": {
'\\.(html)$': '<rootDir>/htmlTemplateMock.html'
}
htmlTemplateMock.html is empty file
For Jest 28+ you can use jest-html-loader to make Jest work with code that requires HTML files.
npm install --save-dev jest-html-loader
In your jest config, add it as a transformer for .HTML files:
"transform": {
"^.+\\.html?$": "jest-html-loader"
},

Importing external module with ES6 syntax and absolute path

So I have a project that looks something like this:
app/
bin/
lib/
src/
main/
submodule.ts
utilities/
common.ts
main.ts
tsconfig.json
gulpfile.js
and app/src/main/submodule.ts needs to import app/src/utilities/common.ts. I am trying to use the ES6 syntax for this. Thus I expect something like this in submodule.ts:
import {common} from '/utilities/common';
Where the root / is app/src/ since that is where tsconfig is found. Yes, app/src/utilities/common.ts does export a module named common.
The problem is that I get "cannot find module '/utilities/common'" errors. I have tried a variety of things:
utilities/common
/src/utilities/common
/app/src/utilities/common
None of these work. A relative path of ../utilities/common does work, but relative paths for common modules is a maintenance nightmare.
It may be worth noting that I just updated from TS 1.5 to 1.6: using utilities/common had worked in 1.5. I cannot find any mention of a breaking change along these lines in the 1.6 notes, though.
I mention the gulpfile.ts and other folders because ultimately I want Gulp to get the TS files from src and put the compiled JS files in bin. I am reasonably confident that I have correctly configured Gulp for this, using gulp-typescript, but for completion's sake, here are my tsconfig.json and gulpfile.js.
tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"noEmitOnError": true
},
"filesGlob": [
"./**/*.ts",
"!./typings/**/*.ts"
]
}
gulpfile.js
var gulp = require('gulp');
var ts = require('gulp-typescript');
var less = require('gulp-less');
var sourcemaps = require('gulp-sourcemaps');
var merge = require('merge2');
var path = require('path');
var tsProject = ts.createProject('src/tsconfig.json', { noExternalResolve: true });
gulp.task('html', function () {
gulp.src([
'src/**/*.html',
])
.pipe(gulp.dest('bin'));
});
gulp.task('typescript', function () {
tsProject.src()
.pipe(sourcemaps.init())
.pipe(ts(tsProject))
.js
.pipe(sourcemaps.write())
.pipe(gulp.dest('bin'));
});
gulp.task('less', function () {
gulp.src([
'src/**/*.less',
])
.pipe(sourcemaps.init())
.pipe(less())
.pipe(sourcemaps.write())
.pipe(gulp.dest('bin'))
});
gulp.task('default', ['html', 'typescript', 'less']);
Finally solved this. Per What's New, 1.6 changed module resolution to behave like Node's. I have not yet investigated Node's module resolution to determine if a fix is possible using that behavior, but I have found a workaround:
The old behavior can be triggered by specifying "moduleResolution": "classic" in tsconfig.json.
Module resolution is performed relative to the current file if the path starts with ./ or ../.
Here is a quick example using:
/
/src/
/src/thing.ts
/main/
/main/submodule.ts
/utilities/
/utilities/common.ts
So the correct statement to import common.ts into submodule.ts would be:
import {common} from '../utilities/common';
You can also use the following root-path (note that there is no leading / or any .s here):
import {common} from 'src/utilities/common';
This works for me in Visual Studio code, with the parent folder of src opened as the working folder. In my case I am targeting ES5 with UMD modules.
You can also resolve a module if it can be found by traversing up from the current location (this is a feature of NodeJS). So you can import thing.ts into submodule.ts using:
import {something} from 'thing';
The resolver will check the current folder, then the parent, then the parent's parent... and so on.
Absolute vs Relative Paths
When it comes to links on web pages, I'm in agreement with you that absolute paths are easier to maintain, especially where resources are shared at multiple levels.
When it comes to modules, I'm not sure I see the same maintenance problem as the paths here are "relative to the file that the import statement appears in" not relative to the web page. I wonder if this may be the application of a very sensible rule in the wrong place.