Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Discussion: Setting up ts_project with custom path mapping in a monorepo #2298

Closed
lencioni opened this issue Nov 20, 2020 · 13 comments · Fixed by #2322
Closed

Discussion: Setting up ts_project with custom path mapping in a monorepo #2298

lencioni opened this issue Nov 20, 2020 · 13 comments · Fixed by #2322

Comments

@lencioni
Copy link
Contributor

lencioni commented Nov 20, 2020

I've been working to set up Bazel with ts_project in a large, custom monorepo (i.e. not using something like Lerna or yarn workspaces). We recently resolved a challenge and I'd like to publicly document it here in case it helps someone else (or if someone sees a better solution for us). Feel free to close this issue.

Our monorepo is set up so that we have a "frontend" directory with a lot of projects as subdirectories under "frontend". The structure is roughly like this:

frontend/
frontend/project-a/
frontend/project-b/
frontend/project-c/
...

Imports inside the same project use relative paths:

import foo from './foo';

And imports from other projects use custom colon-import paths:

import someOtherProject from ':some-other-project';
import anotherThing from ':a-different-project/anotherThing';

We've been running TypeScript without Bazel for a while, and had these custom imports wired up via the following path mapping in our base tsconfig:

{
  "compilerOptions": {
    "paths": {
      ":*": [
        "./frontend/*",
      ],
    }
  }
}

When setting up Bazel, we initially expanded this path mapping to look more like this:

{
  "compilerOptions": {
    "paths": {
      ":*": [
        "./frontend/*",

        // Bazel generates the .d.ts files in the bazel-out directory, so we
        // need to tell TypeScript that it might be able to find them there.
        //
        // This hack was inspired by formatjs:
        // https://github.com/formatjs/formatjs/blob/268d6aef6fc08180a0be691b631eb1cdfb68ca31/tsconfig.json#L19-L41
        // And the rootDirs note in the docs here:
        // https://bazelbuild.github.io/rules_nodejs/TypeScript.html#ts_project
        "./bazel-out/darwin-fastbuild/bin/frontend/*",
        "./bazel-out/k8-fastbuild/bin/frontend/*",
        "./bazel-out/x64_windows-fastbuild/bin/frontend/*",
        "./bazel-out/darwin-dbg/bin/frontend/*",
        "./bazel-out/k8-dbg/bin/frontend/*",
        "./bazel-out/x64_windows-dbg/bin/frontend/*",
      ],
    }
  }
}

This seemed to work okay for some of our projects, however, once we started getting into more complex projects that depended on types that were built from a different project, we started seeing errors in our Bazel ts_project output like this:

frontend/complex-project/foo/bar.ts(27,16): error TS2571: Object is of type 'unknown'.

It seemed that these types ended up as unknown instead of the actual types we expected.

We looked at the .d.ts files that ts_project built for these types, and found code that started like this:

import Foo from ':some-dependency/foo/bar';
// ...

Was built into this:

// In a file in frontend/complex-project
// ...
export declare const FooType: import("../../bazel-out/darwin-fastbuild/bin/frontend/some-dependency/foo/bar").Foo<Bar>;
// ...

We expected the import path to look something like "../../some-dependency/foo/bar" but instead got "../../bazel-out/darwin-fastbuild/bin/frontend/some-dependency/foo/bar", which doesn't really exist. As a result, TypeScript infers it as any which probably gets converted to an unknown somewhere along the line via the generics used here.

After a bit of messing around, we believe that we were able to arrive at an okay solution: add rootDirs and an extra paths mapping like this:

{
  "compilerOptions": {
    "rootDirs": [
      "../..",
      // Ensure that the relative paths in types produced by bazel get turned into
      // "frontend/" paths.
      "../../bazel-out/darwin-fastbuild/bin",
      "../../bazel-out/k8-fastbuild/bin",
      "../../bazel-out/x64_windows-fastbuild/bin",
      "../../bazel-out/darwin-dbg/bin",
      "../../bazel-out/k8-dbg/bin",
      "../../bazel-out/x64_windows-dbg/bin",
    ],

    "paths": {
      ":*": [
        "./frontend/*",

        // Bazel generates the .d.ts files in the bazel-out directory, so we
        // need to tell TypeScript that it might be able to find them there.
        //
        // This hack was inspired by formatjs:
        // https://github.com/formatjs/formatjs/blob/268d6aef6fc08180a0be691b631eb1cdfb68ca31/tsconfig.json#L19-L41
        // And the rootDirs note in the docs here:
        // https://bazelbuild.github.io/rules_nodejs/TypeScript.html#ts_project
        "./bazel-out/darwin-fastbuild/bin/frontend/*",
        "./bazel-out/k8-fastbuild/bin/frontend/*",
        "./bazel-out/x64_windows-fastbuild/bin/frontend/*",
        "./bazel-out/darwin-dbg/bin/frontend/*",
        "./bazel-out/k8-dbg/bin/frontend/*",
        "./bazel-out/x64_windows-dbg/bin/frontend/*",
      ],

      // WARNING: Don't use frontend/ imports, use colon instead. This is for bazel build
      // type resolution: The rootDirs above produce "frontend/" paths in the .d.ts files
      // produced by bazel, and then we remap those paths back into bazel-out here.
      // Note this does mean you can never install a package named "frontend", but that's
      // probably fine since this package is unlikely to be something we'd install:
      // https://www.npmjs.com/package/frontend
      "frontend/*": [
        "./bazel-out/darwin-fastbuild/bin/frontend/*",
        "./bazel-out/k8-fastbuild/bin/frontend/*",
        "./bazel-out/x64_windows-fastbuild/bin/frontend/*",
        "./bazel-out/darwin-dbg/bin/frontend/*",
        "./bazel-out/k8-dbg/bin/frontend/*",
        "./bazel-out/x64_windows-dbg/bin/frontend/*",
      ],
    }
  }
}

This configuration causes our special colon imports to be converted from ":some-project" to "frontend/some-project", which then works because of the second "frontend/*" path mapping.

The main caveat that we've thought of with this approach is that it means we can't just install and use a package named "frontend", but that seems unlikely to cause us any problems.

@mgenov
Copy link

mgenov commented Jan 12, 2021

@lencioni could you provide more details where tsconfig.json files are defined?

@lencioni
Copy link
Contributor Author

Sure thing @mgenov!

For the most part, we currently have a tsconfig.json file in each of our frontend projects. So with the structure I mentioned above, that would be:

frontend/project-a/tsconfig.json
frontend/project-b/tsconfig.json
frontend/project-c/tsconfig.json

We are using project references, and each of these tsconfig.json files extend from a more centralized config in one of our projects that has our global settings in it like the rootDirs and paths stuff I mentioned above. Here's an example of one of these project tsconfig.json files:

{
  "extends": "../typescript/tsconfig.dts.json",
  "include": [".", "./**/*.json"],

  "compilerOptions": {
    "types": ["jest", "node"]
  },

  "references": [
    {
      "path": "../project-b"
    }
  ]
}

We have created some internal tooling that scans the code in our repo for dependencies (currently using jest-haste-map) and keeps parts of these files like the references and compilerOptions.types up to date automatically.

In a few cases today we have some tsconfig.json files more deeply nested in projects. This is mostly to support things in our repo like cypress, which have some different global types that would conflict with other things.

frontend/project-a/tsconfig.json
frontend/project-b/tsconfig.json
frontend/project-b/cypress/tsconfig.json
frontend/project-c/tsconfig.json

We plan to add a lot more tsconfig.json files in our repo, such as in all of our test directories, so that we can improve TypeScript performance and avoid dragging in test-specific global types into production code, but first we have some things we need to solve, such as upgrading our tooling to manage the exclude field for these deeply nested tsconfig.json files. As we roll this out, I believe we will also have some cycles between our test directories that we will need to resolve as well.

@mgenov
Copy link

mgenov commented Jan 13, 2021

Thanks for your feedback @lencioni

I've made a showcase project to try to illustrate this usage but I encountered the following compilation error:

frontend/project-a/index.ts(1,24): error TS2307: Cannot find module ':project-b' or its corresponding type declarations.

when executing

bazel build //frontend/project-a:tsconfig

Could you take a look what could cause the error?

Code showcase is located at: https://github.com/mgenov/bazel-typescript-showcase

@lencioni
Copy link
Contributor Author

I think the baseUrl needs to be a bit different in your repo. I opened a PR that I think fixes it: mgenov/bazel-typescript-showcase#1

@mgenov
Copy link

mgenov commented Jan 13, 2021

Yes, with this change everything is working as expected. Thanks!

lherman-cs pushed a commit to lherman-cs/rules_nodejs that referenced this issue Jan 15, 2021
fix: remove duplicate Importing

chore: upgrade rollup to ^2.3.0

fix: coverage (bazel-contrib#2100)

* test: add coverage e2e test

* fix(builtin): fix coverage lcov merger script jumping out of sandbox and not being able to find c8

* test: don't test coverage on Windows

docs: use @npm//@bazel for example load sites

fix(cypress): allow for async cypress plugins

cypress_repository now fails if cypress verify fails
set the HOME env variable since cypress writes files to it
remove unused includeScreenshots / includeVideos variables
browserify files are no longer included in test output files
screenshots/videos are stored directory in TEST_UNDECLARED_OUTPUTS_DIR

docs: update docs for release

chore(release): 2.0.2

chore: update lock files for release

feat(example): add targets in angular_bazel_architect for production serve and build

fix(examples): use ./ prefix on babel config file

Otherwise if it's in a subfolder, babel will think it's an npm package

chore: update dependency com_google_protobuf to v3.13.0 (bazel-contrib#2103)

refactor(rollup): use rollup loadConfigFile API

chore: update dependency bazel_toolchains to v3.4.1

build(deps): bump elliptic in /e2e/fine_grained_symlinks

Bumps [elliptic](https://github.com/indutny/elliptic) from 6.4.1 to 6.5.3.
- [Release notes](https://github.com/indutny/elliptic/releases)
- [Commits](indutny/elliptic@v6.4.1...v6.5.3)

Signed-off-by: dependabot[bot] <support@github.com>

fix(typescript): only expect .js outs for .tsx? srcs (bazel-contrib#2118)

Fixes bazel-contrib#2115

feat(builtin): new js_library rule (bazel-contrib#2109)

Removes `node_module_library` private API and renames it to `js_library`

the latter will be promoted to a public API in a followup change

fix(typescript): produce .d.ts as default output rather than empty (bazel-contrib#2117)

This lets you type-check a ts_project(emit_declaration_only=True) just by building it (its default outputs)

Fixes bazel-contrib#2116

added script to generate NodeJS versions for node_repositories and added most up-to-date versions (bazel-contrib#2126)

Co-authored-by: Matt Insler <matt.insler@airbnb.com>

refactor: move node version list into its own file (bazel-contrib#2128)

Add a package.json script for updating it

docs: update docs for release

chore(release): 2.0.3

chore: update lock files for release

fix(typescript): add the tsBuildInfoFile option to ts_project (bazel-contrib#2138)

Like other options that affect tsc outputs, Bazel needs to know the value from the tsconfig if its set.
Add it to our validator so there's a buildozer command to sync the option value into the BUILD file.

Fixes bazel-contrib#2137

refactor(typescript): remove private _TsConfigInfo in ts_project (bazel-contrib#2139)

Instead use the same TsConfigInfo that ts_library uses.

Fixes bazel-contrib#1931

docs: refresh docsite

docs: minor cleanup of builtins page

don't include the defaults which are giant dictionaries as they render poorly

docs: fix spacing and link colours on rhs sidenav

Fix circleci status badges to pin to stable branch

CircleCI docs claim that they should use the default branch by default, but this icon is green while stable is red, so I think it's still reporting on master.

ci: all angular examples timeout=long

chore: update dependency bazel_toolchains to v3.4.2

chore: update circleci image to latest to pick up newer chrome

docs: add search to docsite using gcse

feat(typescript): generate tsconfig.json for ts_project (bazel-contrib#2130)

This is an experimental, opt-in feature where ts_project will generate a tsconfig.json file in place of
the user specifying one in the source directory.

I expect a long tail of compatibility bugs since any path appearing in this generated file needs to point from
bazel-out back to the source directory.

Fixes bazel-contrib#2058

docs: replace references to //packages/ with the @npm//@bazel/ equivalent (bazel-contrib#2154)

feat(builtin): accept any stamp vars in pkg_npm

NOTE: instead of replacing the replace_with_version with 0.0.0 in unstamped builds,
we now omit the replacement.

See bazel-contrib#1694

docs(rollup): add stamping and debug to rollup doc

Also move most of the content above the list of rules. It shows up better in the TOC since rollup_bundle
can be its own entry later in the page, and avoids the API doc table of attributes just appearing with no header.

docs: document the node_context_data attribute

It can be useful if you need to turn on/off stamping per-target.
`java_binary` gives a dedicated stamp attribute for this purpose

Fixes bazel-contrib#1693

chore: hide generated .html files in code review

feat(builtin): support for substitutions

fix: use golden_file_test instead

refactor: cleanup pkg_web stamping feature

chore: update dependency bazel_toolchains to v3.5.0 (bazel-contrib#2168)

Updated nodejs versions (14.9.0) (bazel-contrib#2169)

docs: update docs for release

chore(release): 2.1.0

chore: update lock files for release

chore: try github actions version of stale bot

The probot one never triggered despite being setup correctly AFAICT.
This bot seems better supported and I sow it working on bazel-watcher repo.

build(deps): bump http-proxy from 1.18.0 to 1.18.1

Bumps [http-proxy](https://github.com/http-party/node-http-proxy) from 1.18.0 to 1.18.1.
- [Release notes](https://github.com/http-party/node-http-proxy/releases)
- [Changelog](https://github.com/http-party/node-http-proxy/blob/master/CHANGELOG.md)
- [Commits](http-party/node-http-proxy@1.18.0...1.18.1)

Signed-off-by: dependabot[bot] <support@github.com>

build(deps): bump yargs-parser in /e2e/ts_devserver

Bumps [yargs-parser](https://github.com/yargs/yargs-parser) from 13.1.1 to 13.1.2.
- [Release notes](https://github.com/yargs/yargs-parser/releases)
- [Changelog](https://github.com/yargs/yargs-parser/blob/master/docs/CHANGELOG-full.md)
- [Commits](https://github.com/yargs/yargs-parser/commits)

Signed-off-by: dependabot[bot] <support@github.com>

ci: stamp our releases with a stable key

fix(builtin): don't set --preserve-symlinks-main by default (bazel-contrib#2176)

feat: add link_workspace_root to nodejs_binary, npm_package_bin, rollup_bundle, terser_minified, ts_project

Link the workspace root to the bin_dir to support absolute requires like 'my_wksp/path/to/file'.
If source files need to be required then they can be copied to the bin_dir with copy_to_bin.

fix(builtin): fix bazel coverage masking test failures

test(builtin): test failing test with bazel coverage

build(deps): bump http-proxy in /examples/protocol_buffers

Bumps [http-proxy](https://github.com/http-party/node-http-proxy) from 1.18.0 to 1.18.1.
- [Release notes](https://github.com/http-party/node-http-proxy/releases)
- [Changelog](https://github.com/http-party/node-http-proxy/blob/master/CHANGELOG.md)
- [Commits](http-party/node-http-proxy@1.18.0...1.18.1)

Signed-off-by: dependabot[bot] <support@github.com>

build(deps): bump http-proxy in /examples/web_testing

Bumps [http-proxy](https://github.com/http-party/node-http-proxy) from 1.18.0 to 1.18.1.
- [Release notes](https://github.com/http-party/node-http-proxy/releases)
- [Changelog](https://github.com/http-party/node-http-proxy/blob/master/CHANGELOG.md)
- [Commits](http-party/node-http-proxy@1.18.0...1.18.1)

Signed-off-by: dependabot[bot] <support@github.com>

test(rollup): fix test failing due to missing dep

fix(rollup): allow config files to override default onwarn method

Fixes bazel-contrib#2084

feat: link_workspace_root not needed in terser_minified

docs: add spica to adopter organization list (bazel-contrib#2184)

* Add spica to adopter organization list (bazel-contrib#2183)
* docs: update the 'send a PR' link to point to the stable branch

Co-authored-by: Sahin Yort <thesayyn@gmail.com>

feat: promote js_library to public API

Fixes bazel-contrib#149
Fixes bazel-contrib#1771

docs: update docs for release

chore(release): 2.2.0

chore: update lock files for release

Update readme (bazel-contrib#2190)

Fix missing `}` and indentation

feat: add strict_visibility to npm_install / yarn_install rules (bazel-contrib#2193)

With strict_visibility enabled (currently defaults false), only dependencies within the given `package.json` file are given public visibility.

All transitive dependencies are given limited visibility, enforcing that all direct dependencies are listed in the `package.json` file.

closes bazel-contrib#2110

fix: don't glob yarn or node files when using vendored_node or vendored_yarn

- Fixes a visibility issue with rollup-worker

fix(examples): prevent ibazel EOF

Fixes bazel-contrib#2143

docs(karma): document how to use non-headless Chrome (bazel-contrib#2202)

Fixes bazel-contrib#1881

docs(labs): produce stardoc API for labs

Fixes bazel-contrib#2195

fix(karma): allow custom browsers to specify args (fixes bazel-contrib#595)

Today, the args as specified in the various manifests of the rules_webtesting
browsers never make it into the generated karma.conf.js. This results in these
arguments never being used when launching Chrome, preventing customization of
browsers such as window size, enabling remote debugging, or other flag-based
options. This PR fixes this by reading those arguments from the manifest, and
adding them to the browsers list in the generated karma.conf.js.

Also, this PR includes a change to generated_file_test to allow a golden file
to represent a substring of the generated output.

Also Also: This PR includes a golden file test that verified that the generated
karma.conf.js does read in the specified value.

Furthermore, the effect of this can be verified manually via:
```
VERBOSE_LOGS=1 bazel run packages/karma/test/karma:testing_custom_chrome
```
Note the appearance of the additional flags in the new debug output.

fix(builtin): js_library: correctly propagate DeclarationInfos

Transitive typings are added to typings_depsets, but we were checking
the typings array instead.

Signed-off-by: Duarte Nunes <duarte@hey.com>

feat: update nodejs versions (bazel-contrib#2207)

include 10.22.1, 12.18.4, 14.10.0, 14.10.1, 14.11.0 and 14.12.0 in node_versions

Added s390x support

docs: update docs for release

chore(release): 2.2.1

chore: update lock files for release

ci: tell Angular CLI not to update webdriver

It can get ahead of the Chrome version on our CI machine

ci: replace --webdriver-update=false with --no-webdriverUpdate

Architect CLI uses minimist under the hood to parse arguments. Minimist will not convert boolean like values unless they are known options or the `{boolean: true}` option is configured (Which is not in Architect CLI).

feat(karma): use Trusted Types policy when loading scripts for Karma

When the Karma plugin is used in a testing environment that enforces
Trusted Types, its loadFile functionality currently fails due to a
Trusted Types violation when assigning to script.textContent. This makes
it impossible to use the plugin with integration tests that ensure an
application is compatible with Trusted Types.

This is fixed by creating a Trusted Types policy specifically for the
Karma plugin, and use it to promote any loaded scripts to a TrustedScript
before assigning to script.textContent. This is done in a way that is
backwards compatible:
- The policy is `null` in browsers that don't yet support Trusted Types,
  in which case the original script string is used as before.
- When Trusted Types are supported in the browser but not enforced by
  the application, the browser treats the TrustedScript as if it were a
  string when it is assigned to script.textContent.

chore: update dependency bazel_toolchains to v3.6.0

docs: remove HTML tables so docs can be authored in markdown without need for html escaping

docs(rollup): improve clarity

feat(example): add full pwa support

feat(example): service worker update handling

fix(exmaple): add docstring to ngsw_config rule

fix(example): remove server side compression

fix(example): remove index.html from prodapp srcs

fix(example): remove compression dependencies

fix(builtin): js_library supports --output_groups=types

If providing DeclarationInfo we should also give this way for filegroup/bazel CLI to select them

chore: docgen

docs: update docs for release

chore(release): 2.2.2

chore: update lock files for release

fix(builtin): give a longer timeout for _create_build_files

A user reports that their build file generation takes longer than 600 seconds.
It's probably a bug that we are so slow, but let's address that separately (maybe in our work for npm v7)

Also note we could have made this timeout user-configurable, but I think the extra API surface isn't worth the benefit.

Fixes bazel-contrib#2231

fix(typescript): don't include _valid_options marker file in outs

Tested by building //packages/angular:npm_package and don't get an extra .d.ts file in the package.
Also tested the negative case by making an invalid option and check that it's still reported.

Fixes bazel-contrib#2078

chore: allow node versions <= 14.14.0

chore: update rules_docker to 0.14.4

docs: minor update for readability and formatting (bazel-contrib#2243)

* docs: minor update for readibility and formating

Fix small typo in changelog

chore(docs): move ts_library docs into ts_library

Also recommend ts_project for new uses

chore(karma): remove dependency on tmp

feat(typescript): add allow_js support to ts_project

fix(exmaples/nestjs): add module_name field in ts_library

docs: fix a typo of angular-architect example (bazel-contrib#2272)

chore: bump days before closing stale issues to 90

Fix select with conditons on darwin.

Bazel is changing how @bazel_tools/conditions:darwin is implemented.
With old implementation based on flags, it was ok to have darwin and
darwin_x86_64 in a select. This was based on flag --cpu=darwin and
--cpu=dawin_x86_64.

New implementation is based on constraints, where "darwin" means OS (and
any CPU), while "darwin_x86_64" mean only specific CPU. As such they
cannot be used in the same select, because the selection would be
ambiguous.

build: add 'fix-windows' tag due to windows flaky tests

Will revisit the linker and test, but this is blocking PRs from being merged

feat(typescript): worker mode for ts_project (bazel-contrib#2136)

* feat(typescript): worker mode for ts_project

* chore: cleanup and declare protobufjs dependency

* fix: do not pass --watch for non-worker mode

* fix: do not test worker on windows

* fix: log on standalone failures

* chore: docs improvements

Co-authored-by: Alex Eagle <alex.eagle@robinhood.com>
Co-authored-by: Dan Muller <mrmeku@stairwell.com>

feat(node_repositories): Added auth option for downloading nodejs and yarn

fix: npm_package.pack should work in windows os

feat(examples): adds example for running jest with typescript (bazel-contrib#2245)

fix(typescript): specify rootDir as absolute path

Also allow non-ts files across src/bin dir, since they are not emitted we don't need the rootdir
calculation to take them into account. This lets the Angular compiler accept .ts sources from
source dir even if the css inputs are generated.

refactor: ts_project cleanup

feat(cypress): remove browiserify preprocessor

docs: update docs for release

chore(release): 2.3.0

chore: update lock files for release

fix: npm_package.pack on Windows should not generate undefined.tgz

chore: update nodejs versions (bazel-contrib#2284)

perf(cypress): pack cypress runfiles into a single tar

chore: add GitHub Workflow to update NodeJS versions every night

chore: fix a link

Current link returns 404, it seems that the url was somehow changed to .html from .md.

chore: fix the link again

haha

fix(builtin): make linker deterministic when resolving from manifest & fix link_workspace_root with no runfiles

chore: re-lock jest dependencies

It was using a non-standard repository, which had downtime this morning

chore(release): 2.3.1

chore: update lock files for release

chore: update dependency com_google_protobuf to v3.14.0

chore: update dependency bazel_toolchains to v3.7.0

fix launcher script terminating before child terminates on SIGTERM

chore: update dependency bazel_toolchains to v3.7.1

fix(examples): fix jest example on windows

Fixes bazel-contrib#1454

fix(builtin): give better error when linker runs on Node <10

Example how this looks now:

```
[20 / 21] Bundling JavaScript bundle.js [parcel]; 4s remote-cache, darwin-sandbox
ERROR: /private/var/folders/r7/2kp53v7n091gcz93xlt7wtd80000gn/T/tmp-48948DHy4HrXTwhRy/BUILD.bazel:4:1: Bundling JavaScript bundle.js [parcel] failed (Exit 1) parcel.sh failed: error executing command bazel-out/host/bin/external/npm/parcel-bundler/bin/parcel.sh build foo.js --out-dir bazel-out/darwin-fastbuild/bin --out-file bundle.js ... (remaining 2 argument(s) skipped)

Use --sandbox_debug to see verbose messages from the sandbox
ERROR: rules_nodejs linker requires Node v10 or greater, but is running on 8.11.2
Note that earlier Node versions are no longer in long-term-support, see
https://nodejs.org/en/about/releases/
INFO: Elapsed time: 40.360s, Critical Path: 12.97s
INFO: 0 processes.
FAILED: Build did NOT complete successfully
//:test                                                               NO STATUS
```

Fixes bazel-contrib#2304

docs(typescript): link some user-contributed doc (bazel-contrib#2322)

Fixes bazel-contrib#2298

chore: allow node versions >=12 <=14 (bazel-contrib#2332)

chore: allow node versions >=12 <=14

feat: add esbuild package

chore: add module_mapping support via the aspect instead of manual implementing it

chore: sqash

feat: update to latest esbuild, add additional flags when not minifying

fix: consume both JSEcmaScriptModuleInfo and JSModuleInfo to support js_library

fix: add missing bzl libraries and publish helpers

test: use runfiles helper in test

fix: use exe for Windows
@Zemnmez
Copy link

Zemnmez commented Aug 19, 2021

Despite reading all the available documentation I'm still unable to discern what exactly the correct way to do this is.

The documentation only refers to this '../..' stuff:

"compilerOptions": {
    "rootDirs": [
        ".",
        "../../bazel-out/host/bin/path/to",
        "../../bazel-out/darwin-fastbuild/bin/path/to",
        "../../bazel-out/k8-fastbuild/bin/path/to",
        "../../bazel-out/x64_windows-fastbuild/bin/path/to",
        "../../bazel-out/darwin-dbg/bin/path/to",
        "../../bazel-out/k8-dbg/bin/path/to",
        "../../bazel-out/x64_windows-dbg/bin/path/to",
    ]
}

But there's some reference here to a baseUrl above in this thread?

All I've managed to do is get relative imports like ../gen/core_en to work, and only during compilation, not in VSCode, which is left in the dark about the types here.

If the documentation is all to recommend using ts_project, it seems like it should be easier to use than ts_library and ts_binary, which, based on what I've read online it doesn't seem to be.

Can I get clarity on whether 'ts_project' is meant to usable at this point, and how exactly it can be made usable?

Edit: sorry for the tone here, I think I'm hitting a strange edge-case with tsconfig.json where VSCode is not picking it up for some reason.

@Zemnmez
Copy link

Zemnmez commented Aug 19, 2021

With my tsconfig.json and my WORKSPACE in the same folder, I can get the code building with this tsconfig.json:

{
      "extends": "@tsconfig/node14/tsconfig.json",
    // If building without sandboxing, we need to prevent TypeScript from descending into
    // Bazel's external folder which contains third-party Bazel dependencies.
    "exclude": ["external/*"],

    "compilerOptions": {
        "baseUrl": ".",
	"declaration": true,
        "preserveSymlinks": true,
        "paths": {
            "*": [
                "*",
                "bazel-out/x64_windows-fastbuild/bin/*",
                "bazel-out/x64_windows-dbg/bin/*",
                "bazel-out/k8-fastbuild/bin/*",
                "bazel-out/k8-dbg/bin/*",
                "bazel-out/host/bin/*",
                "bazel-out/darwin-fastbuild/bin/*",
                "bazel-out/darwin-dbg/bin/*",
            ]
        },
    }
}

-- with the caveat that for whatever reason this doesn't work for VSCode.

OK -- it looks like though it's compiling successfully, that doesn't mean you can actually run it -- it's failing at runtime, because the require() is failing

Zemnmez pushed a commit to Zemnmez/quickcult that referenced this issue Aug 19, 2021
@Zemnmez
Copy link

Zemnmez commented Aug 19, 2021

Sorry for the spam. I've pushed the repo to https://github.com/Zemnmez/quickcult/tree/broken-monorepo as far as I've managed to get it. yarn bazel_run //solve:main should work but fails at runtime, and VSCode is unable to do code completions.

@bzitzow
Copy link

bzitzow commented Dec 10, 2021

What was the solution for this?

lokshunhung added a commit to lokshunhung/bazel-ts-monorepo that referenced this issue Mar 2, 2022
@Nick-Mazuk
Copy link

@Zemnmez Did you ever manage to figure out VS Code completions?

@bhavitsharma
Copy link

@Nick-Mazuk, here's what I did to get auto-completions:
Added the path/root references as mentioned in the docs. I also symlinked node_modules in WORKSPACE root directory like this, so vscode can find all the respective npm packages and things like eslint, prettier can work:

ln -s /actual/path/to/node_modules node_modules

You can find the actual path to node_modules by doing - $(bazel info output_base)/external/npm/node_modules

@willjschmitt
Copy link

The solutions here worked well before transitions were introduced, but when a rule includes a transition, a generated suffix is added to the output path, such as bazel-out/darwin-fastbuild-ST-4a519fd6d3e4 instead of simply bazel-out/darwin-fastbuild.

We encountered this with rules_docker introducing transitions on container_image in v0.23.0. We aren't benefiting from the transition introduced there, so we are solving this by noop-ing the transition to not introduce an output directory change, for now, but I can imagine where the wider use of platforms and transitions could cause the workaround with hardcoded output directories to become more fragile

@willjschmitt
Copy link

Maybe not super relevant to this discussion, but if others face this type of issue, the way we noop'ed the transition for container_image specifically is:

load("@io_bazel_rules_docker//container:container.bzl", _container = "container")

def _noop_image_transition_impl(settings, attr):
    return settings

_noop_image_transition = transition(
    implementation = _noop_image_transition_impl,
    inputs = [],
    outputs = [],
)

noop_image_transition_container_image = rule(
    attrs = _container.image.attrs,
    executable = True,
    outputs = _container.image.outputs,
    toolchains = ["@io_bazel_rules_docker//toolchains/docker:toolchain_type"],
    implementation = _container.image.implementation,
    cfg = _noop_image_transition,
)

I imagine this could be simpler, but I'm not super familiar with transitions yet.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

8 participants