egoist / bundle-require

bundle and `require` a file, the same way Vite loads `vite.config.ts`
MIT License
172 stars 16 forks source link

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

Closed lvqq closed 1 year ago

lvqq commented 2 years ago

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: https://github.com/egoist/tsup/issues/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 commented 1 year ago

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

github-actions[bot] commented 1 year ago

:tada: This issue has been resolved in version 3.1.1 :tada:

The release is available on:

Your semantic-release bot :package::rocket: