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

[BUG] Custom transformers not working #10028

Closed
chky-nmnsoftware opened this issue Dec 3, 2024 · 2 comments
Closed

[BUG] Custom transformers not working #10028

chky-nmnsoftware opened this issue Dec 3, 2024 · 2 comments

Comments

@chky-nmnsoftware
Copy link

🐛 bug report

When importing and trying to use custom transformers, Parcel will simply refuse to build anything, resulting in a "Cannot find module 'hash'" error.

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

Command for starting server is: node parcel-watch.mjs --port 2004.

parcelrc:

{
    "extends": "@parcel/config-default",
    "transformers": {
        "*.ts": ["./parcel-transformer.mjs", "..."],
        "*.js": ["./parcel-transformer.mjs", "..."]
    }
}

parcel-watch.mjs:

import { Parcel } from '@parcel/core';
import path from 'path';
import { fileURLToPath } from 'url';
import open from "open";

// Required to convert the current module URL to a path
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

async function buildAndRetrieveHashes() {
    // Define the entry file or directory
    const entryFile = path.join(__dirname, 'src/index.html')
    const distDir = path.join(__dirname, 'dist')

    // Define the port
    const portArgIndex = process.argv.indexOf("--port")
    const port = Number.parseInt(process.argv[portArgIndex + 1])
    if (Number.isNaN(port) || portArgIndex < 0) return console.error("🚨 CUSTOM WATCHER ERROR: Port not supplied. Please provide a port using  ")

    // Initialize a new Parcel bundler
    const bundler = new Parcel({
        entries: entryFile,
        defaultConfig: '@parcel/config-default',
        mode: 'development', // 'production' or 'development'
        targets: {
            default: {
                distDir: distDir,
                publicUrl: "."
            }
        },
        serveOptions: {
            port
        },
        hmrOptions: {
            port
        },
        additionalReporters: [
            {packageName: '@parcel/reporter-cli', resolveFrom: __filename}
        ]
    })

    try {
        let opened
        // Tell the bundler to watch the project
        await bundler.watch(async (error, event) => {
            if (error) throw error

            if (event.type === "buildSuccess") {
                // Make placement ts files into JSON
                // await generateJSONFiles(distDir)
                if (!opened) await open(`http://localhost:${port}`)
                opened = true
            } else {
                console.log(event.diagnostics)
            }
        })
    } catch (error) {
        console.error('Build failed:', error);
    }
}

buildAndRetrieveHashes();

parcel-transformer.mjs:

import {Transformer} from '@parcel/plugin'

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

    const lines = code.split('\n')
    let result = []
    let skipNextLine = false

    lines.forEach((line) => {
        if (skipNextLine) {
            skipNextLine = false
            return result.push('')
        }

        if (line.trim().startsWith('//removeOnCompile')) {
            skipNextLine = true
            return result.push('')
        }

        result.push(line)
    })

    asset.setCode(result.join('\n'))
    return [asset]
  }
})

🤔 Expected Behavior

Parcel should successfully compile the files and open the dev server.

😯 Current Behavior

Parcel fails to compile the code and returns the following error:

🚨 Build failed.

@parcel/core: Failed to resolve '8c5bef9247bbbdd5' from './node_modules/pixi.js/lib/environment-browser/browserExt.mjs'

  /home/user/Downloads/ParcelTest/node_modules/pixi.js/lib/environment-browser/browserExt.mjs:16:22
    15 | 
  > 16 | export { browserExt };
  >    |                      ^^
    17 | //# sourceMappingURL=browserExt.mjs.map
    18 | 

@parcel/resolver-default: Cannot find module '8c5bef9247bbbdd5'
[
  {
    message: "Failed to resolve '8c5bef9247bbbdd5' from './node\\_modules/pixi.js/lib/environment-browser/browserExt.mjs'",
    origin: '@parcel/core',
    codeFrames: [ [Object] ]
  },
  {
    message: "Cannot find module '8c5bef9247bbbdd5'",
    hints: [],
    origin: '@parcel/resolver-default'
  }
]

🔦 Context

This issue makes it impossible to write any custom bundlers. Even when using the CLI for building and the most basic form of a transformer, it still returns this errors. The following code also gives the same error:

import {Transformer} from '@parcel/plugin'

export default new Transformer({
  async transform({asset}) {
    return [asset]
  }
})

I know that it is successfully running because it outputs the code when it runs, however, it just refuses to build anything.

My ultimate goal is to make a transformer that will remove any code that follows a comment such as //removeOnCompile or something similar. Unfortunately, there is no way to ensure functionality without Parcel even compiling anything.

💻 Code Sample

https://github.com/chky-nmnsoftware/ParcelTransformerError

🌍 Your Environment

Software Version(s)
Parcel 2.13.2
Node 20.18.0
npm 10.8.2
Operating System Kubuntu 22.04
@chky-nmnsoftware chky-nmnsoftware changed the title Custom transformers not working [BUG] Custom transformers not working Dec 3, 2024
@mischnic
Copy link
Member

mischnic commented Dec 8, 2024

*.{js,mjs,jsm,jsx,es6,cjs,ts,tsx,cts,mts} might work better, for unfortunate implementation specific reasons: #9038

@chky-nmnsoftware
Copy link
Author

*.{js,mjs,jsm,jsx,es6,cjs,ts,tsx,cts,mts} might work better, for unfortunate implementation specific reasons: #9038

That seems to work. I wish it was documented, but oh well. Thank you very much for the help. Hopefully this will help any other people that end up falling victims to this.

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

No branches or pull requests

2 participants