Webpack / typescript require works but import doesn't - import

I'm trying to import a node_module into a TypeScript file. I'm using an adaptation of angular2-webpack-starter for my project structure.
import ace from 'brace';
In one of my files gives me
Cannot find module 'brace'.
But
var ace = require('brace');
Works fine. According to this issue I shouldn't be having any problems.
My webpack config file is copied from angular2-webpack-starter.
My tsconfig.json is as follows
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"sourceMap": true
},
"files": [
"src/bootstrap.ts",
"src/vendor.ts",
"src/polyfills.ts"
],
"filesGlob": [
"./src/**/*.ts",
"!./node_modules/**/*.ts"
],
"compileOnSave": false,
"buildOnSave": false
}
Why would one work but not the other?

The answer is related to this issue. If a module doesn't have type data available (via a .d.ts file), the ES6 module syntax
import name from "module-name";
import * as name from "module-name";
import { member } from "module-name";
//etc
will not work and one must use the CommonJS alternative,
var name = require("module-name");

Related

error on load RestClient on Azure devops extension dev

Im new in extensión dev for #azure #DevOps, I already publish one, the extensión by now can save and get documents via
VSS.getService(VSS.ServiceIds.ExtensionData).then(function (
dataService: any
) {...});
I want to get all teams from the project,and I have 2 problems, First I try to import the Rest client like this:
import RestClient = require("TFS/WorkItemTracking/RestClient");
But, When I upload to azure Devops and display the page in the consle say:
index.js:1 Uncaught ReferenceError: define is not defined
at index.js:1:1
Second I dont relly know how to use the getTeams function, I try this, but I can not test it, If u could give me an example would be great
var client = RestClient.getClient();
client.getTeams(VSS.getWebContext().project.id).then(function(getTeams){console.log(getTeams)})
I try another API and it works like this:
VSS.require(["VSS/Service", "TFS/WorkItemTracking/RestClient"], function (VSS_Service:any, TFS_Wit_WebApi:any) {
// Get the REST client
var witClient = VSS_Service.getCollectionClient(TFS_Wit_WebApi.WorkItemTrackingHttpClient);
// ...
console.log("obtiene cliente")
witClient.getWorkItems(/* some work item IDs */ [1,2,3,4], ["System.Title"]).then(
function(workItems:any) {
console.log(JSON.stringify(workItems));
});
});
But, It doesnt work when I try my first aproach, like this:
import RestClient = require("TFS/WorkItemTracking/RestClient");
I try to check my config files but dont know what to do, I have this in my package.json
"dependencies": {
"vss-web-extension-sdk": "^5.141.0"
},
and in my file tsconfig.json
{
"compilerOptions": {
"target": "es5",
"lib": ["es5",
"es6",
"dom"],
"module": "amd",
"types": ["vss-web-extension-sdk"],
"moduleResolution": "node",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true
}

Differences between Prettier CLI and VSCode extension

I tried to align VSCode extension and my local version of Prettier CLI in my project in order to get same results from both tools.
Prettier VSCode Extension : v9.10.4 (depends on prettier >=2.8.0)
Prettier : v2.8.0
With the following settings
// .vscode/settings.json
{
"prettier.documentSelectors": ["**/*.svg"],
"prettier.resolveGlobalModules": false,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"prettier.requireConfig": true,
"prettier.prettierPath": "./node_modules/prettier",
}
// .prettierrc
{
"printWidth": 80,
"semi": true,
"singleQuote": true,
"trailingComma": "es5",
"arrowParens": "always",
"bracketSameLine": false,
"overrides": [
{
"files": ["*.tsx"],
"options": {
"parser": "typescript"
}
}
]
}
And here is my test file
import * as React from 'react';
function Test() {
const [indicatorStyle, setIndicatorStyle] = React.useState<React.CSSProperties>({});
}
The "Format Document" option from VSCode gives this result
import * as React from 'react';
function Test() {
const [indicatorStyle, setIndicatorStyle] = React.useState<
React.CSSProperties
>({});
}
And the result from Prettier 2.8.0 CLI
import * as React from 'react';
function Test() {
const [indicatorStyle, setIndicatorStyle] =
React.useState<React.CSSProperties>({});
}
What should I do to get the same result instead (the result from Prettier CLI looks better in this case) ?
Thank you.
It seems to be related to a cache problem. After restarting VSCode I get the same results on both tools now!

"Unable to open: File is a directory" when importing

I'm working on a React project in vscode. I noticed a few days ago that any of my imports that point to a directory with an index.js/jsx file in them cannot be resolved by cmd+clicking on the import or the function name.
I get an error in the bottom right "Unable to open : File is a directory"
I have the following in my jsconfig.json file:
{
"compilerOptions": {
"allowSyntheticDefaultImports": false,
"target": "es2017",
"jsx": "preserve",
"baseUrl": ".",
"paths": {
"#/*": [
"src/*"
]
}
},
"exclude": [
"node_modules",
"**/node_modules",
"dist"
]
}
I've tried:
Removing the jsconfig entirely
Various combinations of module import/export patterns
Various combinations of paths/baseUrl/other options in the jsconfig file
Disabling all extensions
Nothing seems to work. The only way I get cmd+click to work is if I point my imports directly at the component itself, or directly at the index.js file.
Does anyone have any insights, please? Googling hasn't shone much light on anything. It's not the end of the world as I cmd+t to most things but it sure is annoying. FWIW Webstorm handles the imports without any issues. Cheers.
EDIT: I forgot to mention. For added spiciness, the cmd+click works for a few seconds while vscode loads. Then "something" happens and it starts throwing the error. Other projects seem to be ok.
I think I may have solved it by adding a tsconfig.json to the project root with the same paths etc. I can now reliably click on import and see function definitions on hover.
If anyone has a similar problem, try the following:
{
"compilerOptions": {
"moduleResolution": "node",
"esModuleInterop": true,
"resolveJsonModule": true,
"baseUrl": ".",
"paths": {
"#/*": [
"src/*"
]
},
},
"include": [
"src/**/**.ts",
"tests/**/*.ts"
],
"exclude": [
"node_modules"
]
}

Unable to use Jest test in svelte component when carbon-icons-svelte is imported from inside node_modules error: Jest encountered an unexpected token

I would like to import an icon from package carbon-icons-svelte to my svelte component. It works very well in browser but I can't test this component. Testes worked good before import of carbon icons.
This is my configuration:
svelte.config.test.cjs
const preprocess = require('svelte-preprocess');
require('dotenv').config()
module.exports = {
preprocess: preprocess({
replace: [[/import.meta.env.([A-Z_]+)/, (importMeta) =>
{ return JSON.stringify(eval(importMeta.replace('import.meta', 'process')))} ]]
})
};
jest.config.cjs
const { pathsToModuleNameMapper } = require('ts-jest/utils');
const { compilerOptions } = require('./tsconfig.json');
module.exports = {
transform: {
'^.+\\.svelte$': [
'svelte-jester',
{
preprocess: './svelte.config.test.cjs'
}
],
"^.+\\.(js)$": "babel-jest",
'^.+\\.(ts)$': [require.resolve('jest-chain-transform'),
{ transformers: ['../../../build-utils/importMetaTransformer.cjs', 'ts-jest'] }
]
},
testMatch: ["**/spec/**/*.js"],
moduleFileExtensions: ['js', 'ts', 'svelte'],
setupFilesAfterEnv: ['<rootDir>/jest-setup.ts'],
moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths, {prefix: '<rootDir>/'})
};
tsconfig.json
{
"compilerOptions": {
"moduleResolution": "node",
"module": "es2020",
"lib": ["es2020", "DOM"],
"target": "es2019",
"importsNotUsedAsValues": "error",
"allowSyntheticDefaultImports": true,
"isolatedModules": true,
"resolveJsonModule": true,
"sourceMap": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"baseUrl": ".",
"allowJs": true,
"checkJs": true,
"paths": {
"$/*": ["src/*"]
}
},
"include": [
"src/**/*.d.ts",
"src/**/*.js",
"src/**/*.ts",
"src/**/*.svelte",
"src/**/*.svelte-kit",
"./jest-setup.ts"
],
"exclude": ["node_modules"]
}
I have this information about an error in jest:
Test suite failed to run
Jest encountered an unexpected token
Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.
Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.
By default "node_modules" folder is ignored by transformers.
Here's what you can do:
• If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/configuration
For information about custom transformations, see:
https://jestjs.io/docs/code-transformation
Details:
/home/dev/src/iroco-app-client/node_modules/carbon-icons-svelte/lib/Information32/Information32.svelte:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){<script>
^
SyntaxError: Unexpected token '<'
9 | import { createPopper } from '#popperjs/core';
10 | import Information32 from 'carbon-icons-svelte/lib/Information32/Information32.svelte';
> 11 |
| ^
I added to jest.config.test.cjs
transformIgnorePatterns: ["<rootDir>/node_modules/(?!(carbon-icons-svelte))"]
after moduleNameMapper but still it doesn't work.
Thanks for your help.
running on node 16, i changed my babel to cjs and it worked for me, this is what it looks like
module.export = {
presets: [['#babel/preset-env', { targets: { node: 'current' } }], '#babel/preset-typescript']
};
my jest.config.js
const config = {
testEnvironment: 'jsdom',
transform: {
'^.+\\.js$': 'babel-jest',
'^.+\\.ts$': 'ts-jest',
'^.+\\.svelte$': ['svelte-jester', { preprocess: true }]
},
transformIgnorePatterns: [
'<rootDir>/node_modules/(?!(carbon-icons-svelte))',
'<rootDir>/node_modules/(?!(carbon-components-svelte))'
],
moduleFileExtensions: ['js', 'ts', 'svelte']
};
export default config;

vscode Prettier not working after update vscode v1.53

I have been using vscode prettier for few months now. I always used it to auto format my codes with vscode shortcut Shift + Alt + F or type >Format Document in command palette
But all of a sudden, vscode gave me this error this error msg: "invalid prettier configuration file detected. See log for details.". This happend after update vscode to v1.53
When I click on "show Log". It show me this:. (It is much much more longer of cause, but I think here is the most import part)
["ERROR" - 2:50:11 PM] Invalid prettier configuration file detected.
["ERROR" - 2:50:11 PM] Must use import to load ES Module: /home/koonfoon/git-repos/koonfoon/someRepo/.prettierrc.js
require() of ES modules is not supported.
require() of /home/koonfoon/git-repos/koonfoon/someRepo/.prettierrc.js from /home/koonfoon/.vscode-server/extensions/esbenp.prettier-vscode-5.9.1/node_modules/prettier/third-party.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 .prettierrc.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /home/koonfoon/git-repos/koonfoon/someRepo/package.json.
Inside my package.json has value "type": "module".
This is how my .prettierrc.js looks like:
// .prettierrc.js
module.exports = {
semi: true,
trailingComma: "all",
singleQuote: true,
printWidth: 120,
tabWidth: 4
};
.eslintrc.js:
// .eslintrc.js
module.exports = {
"env": {
"commonjs": true,
"es2021": true,
"node": true
},
"extends": [
//"eslint:recommended",
"plugin:#typescript-eslint/recommended",
"prettier/#typescript-eslint",
"plugin:prettier/recommended"
],
"parser": "#typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 12,
"sourceType": "module"
},
"rules": {
}
};
Please note: it was working fine until vscode updated to v1.53
My repo is written in typescript.
I have no ideal what cause this error.
Please help.
Thank you.