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

replaceDirnamePlugin will crash while string includes import.meta.url #32

Closed
lvqq opened this issue Sep 17, 2022 · 2 comments
Closed

replaceDirnamePlugin will crash while string includes import.meta.url #32

lvqq opened this issue Sep 17, 2022 · 2 comments
Labels

Comments

@lvqq
Copy link

lvqq commented Sep 17, 2022

I find bundle-require uses a custom esbuild plugin to handle path, source code is:

export const replaceDirnamePlugin = (): EsbuildPlugin => {
  return {
    name: "bundle-require:replace-path",
    setup(ctx) {
      ctx.onLoad({ filter: JS_EXT_RE }, async (args) => {
        const contents = await fs.promises.readFile(args.path, "utf-8")
        return {
          contents: contents
            .replace(/[^"'\\]\b__filename\b[^"'\\]/g, (match) =>
              match.replace("__filename", JSON.stringify(args.path)),
            )
            .replace(/[^"'\\]\b__dirname\b[^"'\\]/g, (match) =>
              match.replace(
                "__dirname",
                JSON.stringify(path.dirname(args.path)),
              ),
            )
            .replace(/[^"'\\]\bimport\.meta\.url\b[^"'\\]/g, (match) =>
              match.replace(
                "import.meta.url",
                JSON.stringify(`file://${args.path}`),
              ),
            ),
          loader: inferLoader(path.extname(args.path)),
        }
      })
    },
  }
}

Here has a problem while a string including keywords like __filename, __dirname or import.meta.data, the path in string is handled too. See the example in tsup.config.ts using banner: egoist/tsup#719.

So maybe we need to add logic to exclude path in string. But regexp match seems hard to judge if the path reference is in string or not. Is there any quick way to fix this problem? AST may do, but it complicates the logic of the plugin.

@egoist
Copy link
Owner

egoist commented Nov 3, 2022

figured out a way to do this using esbuild's define option and inject some code by peeking Vite's source code: https://github.com/vitejs/vite/blob/51ed05915ae1fcebacd5bcebca76559a2b8e4473/packages/vite/src/node/config.ts#L1013

@egoist egoist closed this as completed in 9a45f9f Nov 3, 2022
@github-actions
Copy link

github-actions bot commented Nov 3, 2022

🎉 This issue has been resolved in version 3.1.1 🎉

The release is available on:

Your semantic-release bot 📦🚀

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

No branches or pull requests

2 participants