modernweb-dev / web

Guides, tools and libraries for modern web development.
https://modern-web.dev
MIT License
2.18k stars 278 forks source link

dev-server-esbuild Side Effect Imports #1477

Open Marshal27 opened 3 years ago

Marshal27 commented 3 years ago

I have an Open-WC generated typescript monorepo with Lerna on top; I am using the esbuild plugin for the dev server per the recommendation in the documentation.

I am struggling to import the side effect from an NPM package dev dependency using the esbuild plugin.

esbuild settings

 plugins: [
    esbuildPlugin({ 
      ts: true, 
      json: true,
      target: 'auto' })
  ],
// this import works, adds .js to the end of index in the url on the network call
// this imports the exported class and works well.
import '@npm-alias/index';

// does not work, no .js extension is added on network call
import '@npm-alias/index/dist/sideEffect';

// adding .js to the end explicitly, will add .ts extension on the network call
// this generates a 404 because there is no .ts file at this level in the node_modules
// adding .ts incorrectly I believe
import '@npm-alias/index/dist/sideEffect.js';

// below works and adds the .js extension correctly
// but this is not a viable import once the package has been published
import '../../../node_modules/@npm-alias/index/dist/sideEffect';
claviska commented 2 years ago

I ran into this today and the title should probably be "esbuild plugin does not follow TypeScript path aliases" as it's a more generic issue.

It's pretty common to use path aliases:

import something from '~/path/to/something';

// vs.

import something from '../../../something';

TypeScript supports this in tsconfig.json, e.g.

{
  "compilerOptions": {
    "paths": {
      "~/*": [
        "src/*"
      ],
    }
  }
}

When used, esbuild will honor this syntax and things "just work." However, when used with WTR, the following error occurs:

Error while transforming [source file]: Could not resolve import "~/path/to/something".

It seems like WTR's esbuild plugin isn't aware of the tsconfig.json, so having the ability to customize the config through the plugin API would be one way to mitigate this. Perhaps a more convenient solution would be to look for tsconfig and automatically pass compilerOptions.paths to esbuild.

@LarsDenBakker I'm not familiar with WTR's codebase. Do either of these sound like a reasonable option? Can you think of a better approach to make this work?

If you'd like a test repo, let me know and I'll set one up.

kobleistvan commented 2 years ago

Any update on this issu?

phosph commented 2 years ago

I found on the esbuild page that compilerOptions.paths are honored only when bundling is enabled

All other fields will be ignored. Note that import path transformation requires bundling to be enabled, since path resolution only happens during bundling.

https://esbuild.github.io/content-types/#tsconfig-json