Skip to content

Dependency assets are not recognized if a declare function require(...) exists #10208

@balthild

Description

@balthild

🐛 bug report

One of the typescript files from a vendor package contains code like this...

declare function require(x: string): any
const url = require('../../some-text-file.txt')

The typescript files use ESM import in general, but use require sometimes to import asset files.

The some-text-file.txt is not added into the bundle graph and does not appear in the dist folder.

🎛 Configuration (.babelrc, package.json, cli command)

.parcelrc

{
  "extends": "@parcel/config-default",
  "transformers": {
    "*.txt": ["...", "@parcel/transformer-raw"],
  },
}

package.json

{
  "targets": {
    "flame": {
      "source": "./resources/js/flame.tsx",
      "distDir": "./dist",
      "context": "browser",
      "outputFormat": "global",
      "sourceMap": true,
      "scopeHoist": false
    }
  }
}

Note that scope hoisting is turned off because I was also encountering #6071. However, if I turn it on, the txt file will be bundled correctly. Not sure if the two problems are correlated or not.

🤔 Expected Behavior

The some-text-file.txt should be a dependency of the typescript file.

😯 Current Behavior

An Uncaught error: Cannot find module occurs at runtime.

💁 Possible Solution

I wrote a transformer plugin as a workaround

import { Transformer } from '@parcel/plugin';

export default new Transformer({
  async transform({ asset }) {
    const code = await asset.getCode();

    let match = code.match(/require\('(.+\.txt)'\);/);
    if (match) {
      asset.addDependency({
        specifier: match[1],
        specifierType: 'url',
        bundleBehavior: 'isolated',
      });
    }

    return [asset];
  },
});

🔦 Context

💻 Code Sample

🌍 Your Environment

Software Version(s)
Parcel 2.15.4
Node 22.16.0
npm/Yarn yarn 4.6.0
Operating System macOS 15

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions