webpack / webpack-sources

Source code handling classes for webpack
MIT License
261 stars 71 forks source link

Expose _name as public property #154

Closed steverep closed 6 months ago

steverep commented 6 months ago

The _name class property has no type. It would also be useful to expose this more publicly without the underscore.

alexander-akait commented 6 months ago

We don't have types here, please open an issue in @types/webpack-sources repo

steverep commented 6 months ago

I didn't realize there were no types here at first, so 👍🏻 to that. However, exposing the name as a public property or getter must be done here. And it looks like the @types package doesn't bother with any of the pseudo-private fields.

alexander-akait commented 6 months ago

We have getName to get name

steverep commented 6 months ago

We have getName to get name

Looks like that's only on OriginalSource and ReplaceSource, but missing from SourceMapSource. Maybe it should be on the base class and return null or undefined if the subclass doesn't have it?

alexander-akait commented 6 months ago

Because not all sources require it

steverep commented 6 months ago

😕 but it's required in the SourceMapSource constructor. Here's my simple use case where I extract the existing source and map, transform it, then reconstruct it with the new source and map:

      hooks.renderModuleContent.tap(
        PLUGIN_NAME,
        (source, module, { chunk, moduleGraph }) => {
          // ...
          const { source: origCode, map: origMap } = source.sourceAndMap();
          const { code, map } = transformSync(origCode as string, /* options */)!;
          // @ts-expect-error _name is incorrectly missing from type
          return new SourceMapSource(code!, source._name as string, map!);
        },
      );

I simply want to make sure it keeps the same name.

alexander-akait commented 6 months ago

hm, can you provide why do you need it? You don't use CachedSource?

steverep commented 6 months ago

I'm not sure how CachedSource would help here. The code snippet above simply extracts the current source code and map, passes it to Babel to manipulate, then reconstructs a new Source instance to return back to Webpack.

alexander-akait commented 6 months ago

I see, do you want to send a PR, let's implement getName like here https://github.com/webpack/webpack-sources/blob/main/lib/OriginalSource.js#L22, is it fine for you?

steverep commented 6 months ago

Yeah I can add it 👍🏻.

Also, to be fully correct on types, the Webpack hooks that receive a source like renderModuleContent are typed as Source, but they really should have type SourceMapSource | RawSource.

alexander-akait commented 5 months ago

It can be also ConcatSource, so I think the Source type are better there