Bit will not find modules located within tsconfig's srcDir property - javascript

My bit build cannot locate various modules and fails:
$ bit build
Command failed: node /Users/me/Documents/repos/my-project/.git/bit/components/compilers/angular/bit.envs/0.2.0/node_modules/ng-packagr/cli/main.js -p ng-package.json -c tsconfig.json
ERROR: button/button.component.ts(13,38): error TS2307: Cannot find module 'app/services/my-service-a.service'.
button/button.component.ts(14,25): error TS2307: Cannot find module 'app/services/models/'.
etc . . .
I am thinking that it cannot find modules that live within src/app that are just referenced use app, eg:
import { IMyInterface } from 'app/services/models/';
This works in the project because tsconfig.json contains the property
"srcDir": "src"
so app/ within the component actually references src/app
However, the first line of the error seems to be the full bit command with some default settings explicitly written out. There is written:
-p ng-package.json -c tsconfig.json
Well, I have no idea about ng-package.json. This is not in my project. But the tsconfig.json which contains the srcDir property lives at the same level in my project as I ran bit build from, so the -c argument looks correct.
How can I instruct Bit to find modules located within srcDir?
Also, I can't find a tag for Bit, so if anyone can help me out with that, thanks. Further, if any maintainers of Bit read this, I need to tell you that your name is really difficult to Google errors for. It's too short and far too common a word. Any search advice in this area would be welcome.

Related

webpack require with dynamic path

My colleague put something like this in our code:
const information = require('../relative/path/' + tag + '.json');
The funny thing is that it works, and I don't really see how.
I have created this minimal project:
$ head *.json main.js
==> 1.json <==
["message #1"]
==> 2.json <==
["message two"]
==> 3.json <==
["message III"]
==> package.json <==
{
"dependencies": {
"webpack": "^5.38.1"
"webpack-cli": "^4.7.2"
}
}
==> package-lock.json <==
...
==> main.js <==
const arg = process.argv[2] ? process.argv[2] : 1;
console.log(require(`./${arg}.json`)[0]);
when I run the original program, I get this:
$ node main.js 1
message #1
$ node main.js 2
message two
$ node main.js 3
message III
so now I compile with webpack
$ node_modules/.bin/webpack ./main.js
and it creates a dist directory with a single file it in, and that new bundled program works too:
$ node dist/main.js 1
message #1
$ node dist/main.js 2
message two
$ node dist/main.js 3
message III
and when I look inside the bundle, all the info is bundled:
When I remove the require from the program, and just print the arg, the bundled program is a single line.
So how does it do it?
somehow calculate every possible file?
just include everything from the current directory down?
Funny thing is in my simple example, package.json ended up in there too, but in the real one that gave me the idea, it didn't.
Does anybody know how this works?
I mean the simple practical answer for me is, never put variables in require... but I am still curious.
PS the real one is a web project. just used node and args for the example
Webpack always bundles all require'd files into the final output file (by default called bundle.js). You cannot require anything that was not bundled.
If you require something that is not a constant, as you pointed out, it might lead to some trouble. That is why eslint has a no-dynamic-require rule for that. But if you know what you are doing, everything is just fine.
Webpack uses some heuristics to support non-build-time-constant values (i.e. expressions) for require. The exact behavior is documented in webpack's documentation on dependency management.
As explained in that link, your require('../relative/path/' + tag + '.json') will lead webpack to determine:
Directory: ../relative/path
Regular expression: /^.*\.json$/
And will bundle all files matching that criterion.
When your require call is executed, it will provide that file that matches it exactly, or throw an error if that file was not bundled.
Important: This means, of course, that you cannot add files after bundling. You must have files in the right place, before bundling, so they can be found, added and ultimately resolved by webpack.
Also note that often times, you don't need to write your own webpack experiments. Webpack has plenty of official samples. E.g. your case is illustrated exactly by this official webpack sample.

How can I get TypeScript-aware autocomplete working with JavaScript files and a `#types` package?

In looking to use a new fairly large project (Three.js) and for teaching beginners, I can see the appeal of auto-complete.
However, for Atom, even with the atom-typescript package, I'm not finding very clear guidance on how to set this up (I have some familiarity with TypeScript syntax but am not used to setting it up myself.). I'd expect for something as useful as type-aware autocomplete for JavaScript, there might be some quick-start tutorials out there for just this use case, but I have not found anything which has helped get things working.
According to https://www.typescriptlang.org/docs/handbook/declaration-files/consumption.html , I'd expect I should just be able to run:
pnpm i -D #types/three
...(using pnpm as my package manager) and then add the import (if the THREE global isn't defined by the #types/three package):
import * as THREE from 'three';
I also ran pnpm i -D typescript figuring Atom might want to access a local copy.
Adding a jsconfig.json with the following (in the root directory with my other files and package.json) did not help:
{
"compilerOptions": {
"lib": ["es2015", "dom"]
}
}
And in atom-typescript I have enabled "Enable Atom-TypeScript for JavaScript files (experimental)". The only other package with "typescript" in the name that I have is "language-typescript" (and I've disabled "ide-typescript").
Even if I need to set up my own declaration file, shouldn't I be getting errors?
Adding a declaration file of my own didn't seem to change anything though. threed.d.ts:
declare module "threed" {
}
I'd expect at least errors about not having types, but not getting anything.
And I also added the following to my ~/.atom/init.coffee file as per https://github.com/TypeStrong/atom-typescript/blob/master/docs/faq.md#i-want-to-use-atom-typescript-with-javascript-too :
#CHANGE THE PACKAGE NAME IN THE NEXT LINE IF YOU'RE USING
#A DIFFERENT GRAMMAR PACKAGE
do (grammarPackageImUsing = "language-javascript") ->
atom.packages.onDidTriggerActivationHook "#{grammarPackageImUsing}:grammar-used", ->
atom.packages.triggerActivationHook 'language-typescript:grammar-used'
...and did a restart.
I also tried command-shift-P and TypeScript: Activate. Nothing. What am I missing?

how can I setup #types for a third party react javascript module so I can access it from typescript and package it with webpack?

There is a 3rd party all-javascript npm scoped package, let's call it #foo, with a module inside called bar. I wanted to use the react component #foo/bar/X from within my typescript .tsx file. I immediately ran into "module not found" when I tried to import X from '#foo/bar/X'. How can I resolve this using #types typescript to resolve the module X and get webpack to run without errors?
My starting point was this introduction on how to how to use react and webpack with typescript: https://www.typescriptlang.org/docs/handbook/react-&-webpack.html. However, said instructions do not tackle the problem that the react component I want to use has no #types. So my first step is I needed to add #types.
There was one important nuance about the scoped module #foo/bar, which was that it broke all its subcomponents into individual sub modules like #foo/bar/X, #foo/bar/Y, and #foo/bar/Z with #foo/bar itself having no functionality. As we will see that was an important nuance which made solving this a bit trickier than if I had not had to import a scoped module into my typescript.
There is a nice blog post here about how to import a vanilla javascript into typescript. Unfortunately there is a shortcoming to the proposed approach. Namely, the idea of adding "index.d.ts' to a src/#typings has two problems:
It works only for running the typescript compiler (tsc) locally. That is to say it will make tsc happy, by allowing tsc to resolve the module from your your local ".d.ts" file, but webpack will still fail with module not found.
The proposed approach didn't teach me how to deal with scoped modules which have different rules for how folders under #types are named
Whatever approach I tried, I knew I needed to have this import statement in my typescript file:
import X from '#foo/bar/X';
ReactDOM.render(
<X/>,
document.getElementById("example")
);
Somewhere, I needed to have the following in a ".d.ts" declarations file like index.d.ts, that much was obvious:
declare module '#foo/bar';
declare module '#foo/bar/X';
But running 'webpack' yielding Module not found: Error: Can't resolve '#foo/bar/X'
I decided to run the typescript compiler (tsc) with this flag to see the possible places where tsc would try to resolve the module.
tsc --traceresolution
Using the traceresolution flag I was able to see something very interesting: that the location under node_modules/#types where tsc searches was quite unexepected (and thereby where webpack searches, since webpack follows the same rules as tsc). It was expecting to find my index.d.ts file under node_modules/#types/foo__bar NOTE THE DOUBLE UNDERSCORE. That's right, for scope packages, you cannot have node_modules/#types/#foo/bar/index.d.ts. Instead you must use a single folder under #types named foo__bar with DOUBLE UNDERSCORE.
With this knowledge I created #types/foo__bar. I copied package.json from the #foo/bar module into #types/foo__bar. I cleaned out all the scripts and other useless stuff that the #types would not need, and stripped it down to this:
{
"name": "#types/#sfoo/bar",
"version": "2.6.0",
"peerDependencies": {
"react": "^16.3",
"react-dom": "^16",
"styled-components": "^3"
},
"dependencies": {
...
},
"engines": {
"node": ">=6"
},
"gitHead": "ac0288aaa47a4f15e56db3a5eff4424fb7905419",
"main": "",
"types": "index"
}
But yet there was one more problem! Even after tsc could resolve my #types, webpack still yielded module not found: can't resolve #foo/bar. So why the heck can't webpack find it? Again, I found a flag that could show me more:
webpack --verbose
But here I had less luck since the webpack rules were just like the typescript rules for module resolution. However from the --verbose output I did notice that one file webpack was interested in was node_modules/#foo/bar/index.js. However, the bar module lacked any index.js since it was really just an empty enclosing module around submodules like #foo/bar/X. Whether this is a bug or a feature of webpack, I don't know, but ADDING AN EMPTY index.js to node_modules/#foo/bar pacified webpack, and my simple example now worked with component X displayed in the browser when I loaded the HTML page.

Unable to compile and publish my Typescript library using webpack or TSC

Ive created a library that helps to trace an object state using rx streams and
Im trying to publish it to npm community.
you can check this out In my github repo
I want to compile my library to a single Javascript file and also create a declaration file ".d.ts" for Typescript users.
As i understand, when running $ npm publish i release my entire repository. what i want is to release the dist folder with the library source and declaration file and so the end users will be able to debug my library if necessary through their code so i need also source map.
So first i need to compile my src directory to a single javascript file and i have 2 ways to do so, using tsc or with webpack.
What ive tried so far and you should know:
I used module alias, configured in tsconfig.json.
I separated the library's bussiness logic to multiple files.
I wanted to import internal library's modules using "#lib" prefix.
so in my tsconfig.json i added:
"paths": {
"#lib/*": [
"src/*"
]
},
That alone cause some problems.
first of all running the command:
$ tsc src/index.ts
doesn't work at all and it shows me an error:
src/index.ts(3,15): error TS2307: Cannot find module '#lib/state-traceable'.
src/index.ts(4,15): error TS2307: Cannot find module '#lib/traceable-decorator'. src/index.ts(5,15): error TS2307: Cannot find module '#lib/effect-decorator'.
src/index.ts(6,15): error TS2307: Cannot find module '#lib/meta'.
yet running the command:
$ tsc
does actually works but it compiles each source file and create declaration file for each one of them.
Additionally, it preserves the path alias "#lib/*" instead of compiling it to something javscript compatible with relative paths "../", "./" etc...
Using webpack:
I succeed to bundle all my library sources to a single file and get rid of the "#lib" prefix however im not able to create a single declaration file.
im using "awesome-typescript-loader" plugin for webpack.
I created an issue, thought its a bug but i yet received any response from them:
https://github.com/s-panferov/awesome-typescript-loader/issues/559
Also tried to get some help from Gitter chats, Typescript community, "awesome-typescript-loader" library has no dedicated chat but couldn't find any useful information. Most of the examples ive seen, Typescript library publishers used to create a single file in their source directory: "index.ts" and it makes life easier because you can use tsc and compile that single file to a javascript file.
I hope i will find salvation here.
Some general info about the environment itself:
OS: Windows 10 Pro
Node Version: 9.5.0
npm version: 5.6.0
webpack version: 4.2.0
Please use the path configuration like below
"paths": {
"#lib/state-traceable": ["src/state-traceable.ts"],
"#lib/meta": ["src/meta.ts"],
"#lib/effect-decorator": ["src/effect-decorator.ts"],
"#lib/traceable-decorator": ["src/traceable-decorator.ts"],
"#lib/contracts/*": ["src/contracts/*"],
"#lib/utils/*": ["src/utils/*"],
"#lib/rx-operators/*": ["src/rx-operators/*"]
},

How to create aurelia typescript project with vs2017rc

I am new to aurelia, and I need create a prototype project of the framework. At the beginning, I planed to use skeleton-typescript-aspnetcore skeleton, but when I tried the vs2017rc, I found it uses .csproj as the default format(while vs2015 is project.json/.xproj), I think we should follow the vs2017 because we will upgrade our IDE after it's been launched.
The vs2017 have a wizard to upgrade .xproj project, but after the upgrading(skeleton-typescript-aspnetcore), there still lots of error ahead me...
I also tried aurelia-cli, but seems it has not support vs2017 yet, does anyone could give a guide to create the prototype project? I will integrate some plugins like the skeleton mentioned above, such as gulp,karma,breeze...
thank you in advance.
Since Visual Studio 2017 just launched I thought I'd answer how I solved this, as there are still many errors when using "skeleton-typescript-aspnetcore".
Using https://github.com/aurelia/skeleton-navigation/releases/tag/1.1.2 as a starting point, these are the steps to get it running:
When you first run the project you will get errors complaining that some files located in /test/ is not under 'rootDir'. In your tsconfig.json the rootDir is defined as "src/", this can be solved simply by moving your test folder inside your src folder. This will cause new errors because the paths defined in those files has now changed. You will need to edit app, child-router and users imports like this:
import {Users} from '../../users'; IntelliSense should help you out here.
The command gulp test will also not run before changing to the new path, you can change the path in karma.conf.js:
files: [
'src/test/unit/setup.ts',
'src/test/unit/*.ts'
],
Next the file users.ts will throw errors like Type 'Response' is not assignable to type 'any[]'. You will need to tell TypeScript what you're declaring like this: public users : Object = []; or simply: public users = {};
The final problem is that you're going to have a lot of duplicate identifier errors, at the time of writing this the cause of this seems to be from the changes brought on by TypeScript version 2.2.1. I don't know what specifically breaks, but I know that previous version 2.1.5 still works. So what you need to do is to run npm install typescript#2.1.5 --save in your src/skeleton directory, the --save is just to update your package.json file, you can do this on your own later as well if you wish.
After you've done that your gulp errors (20~ of them) should be resolved. But there are still some errors remaining caused by duplicate signatures. Again, things have changed in TypeScript 2.0+, there is now a simplified way of getting and using declaration files. Here is an answer on SO on how to use the #types feature: How should I use #types with TypeScript 2 , but to keep this short and sweet you will have to go to your tsconfig.json file and explicitly tell where to find the #types/node folder. It would look something like this:
"compilerOptions": {
...
"typeRoots": [
"node_modules/#types"
],
"types": [ "node" ]
...
},
Hope this helps, with these changes the project should now build and launch correctly.
EDIT:
I recently ran into some problems again with building my project. I got a lot of duplicate identifiers again... I however ran across this answer on SO: TypeScript throws multiple duplicate identifiers
Apparently TypeScript latest ships with fetch definitions out of the box, so I was able to run the command from the answer in the link:
npm uninstall #types/whatwg-fetch
And upgrading from typescript 2.1.5 to latest:
npm install typescript --save
You might even want to install typescript globally by appending -g.
Also this will continue to be an issue unless you comment out/delete url and whatwg-fetch from typings.json globalDependencies in order to prevent it from recreating itself:
"globalDependencies": {
//"url": "github:aurelia/fetch-client/doc/url.d.ts#bbe0777ef710d889a05759a65fa2c9c3865fc618",
//"whatwg-fetch": "registry:dt/whatwg-fetch#0.0.0+20160524142046"
}
Then you can either delete the typings folder, running typings install again or edit index.d.ts in the typings folder and delete the reference paths to whatwg-fetch and url.
Hope this helps someone who might've encountered the same problems even after "fixing" it.

Categories

Resources