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

import.meta.require is not a function error after target: "node" build #5707

Closed
Dugnist opened this issue Sep 18, 2023 · 5 comments
Closed
Labels
bug Something isn't working bundler Something to do with the bundler

Comments

@Dugnist
Copy link

Dugnist commented Sep 18, 2023

What version of Bun is running?

1.0.2+37edd5a6e389265738e89265bcbdf2999cb81a49

What platform is your computer?

Linux 6.2.0-32-generic x86_64 x86_64 Ubuntu 22.04.3 LTS

What steps can reproduce the bug?

  1. Create a /cli/build.ts file:
import path from "node:path";
import process from "node:process";

const projectBaseDir = process.cwd();

const input = path.resolve(
  projectBaseDir,
  "packages/name-of-package/src/production.ts"
);
const output = path.resolve(projectBaseDir, "build");

await Bun.build({
  entrypoints: [input],
  outdir: output,
  target: "node",
  format: "esm",
});
  1. Run bun run ./cli/build.ts
  2. Created /build/production.js
  3. Run node ./build/production.js
  4. Got an Error:
file:///home/.../build/production.js:19
  return import.meta.require(id);
                     ^

TypeError: (intermediate value).require is not a function
    at __require (file:///home/.../build/production.js:19:22)
    at file:///home/.../build/production.js:3437:12
    at file:///home/.../build/production.js:17:45
    at file:///home/.../build/production.js:31587:15
    at file:///home/.../build/production.js:17:45
    at file:///home/.../build/production.js:31685:30
    at ModuleJob.run (node:internal/modules/esm/module_job:217:25)
    at async ModuleLoader.import (node:internal/modules/esm/loader:308:24)
    at async loadESM (node:internal/process/esm_loader:42:7)
    at async handleMainPromise (node:internal/modules/run_main:66:12)
  1. build/production.js code generated by bun before main logic:
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getProtoOf = Object.getPrototypeOf;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __toESM = (mod, isNodeMode, target) => {
  target = mod != null ? __create(__getProtoOf(mod)) : {};
  const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
  for (let key of __getOwnPropNames(mod))
    if (!__hasOwnProp.call(to, key))
      __defProp(to, key, {
        get: () => mod[key],
        enumerable: true
      });
  return to;
};
var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
var __require = (id) => {
  return import.meta.require(id);
};
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, {
      get: all[name],
      enumerable: true,
      configurable: true,
      set: (newValue) => all[name] = () => newValue
    });
};
var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);

What is the expected behavior?

node ./build/production.js should work. Require should handle ESM imports.

What do you see instead?

TypeError: (intermediate value).require is not a function

Additional information

I made a temporary solution:

/cli/build.ts

...

// Temporary solution to fix bun build "import.meta.require" error
const pathToBuildedFile = path.resolve(projectBaseDir, "build/production.js");

const inputFile = Bun.file(pathToBuildedFile);
const outputFile = Bun.file(pathToBuildedFile);

let inputFileText = await inputFile.text();

if (!inputFileText.includes('import { createRequire } from "module";')) {
  inputFileText = inputFileText.replace(
    "var __require = (id) => {",
    'import { createRequire } from "module"; var __require = (id) => {'
  );
}

if (!inputFileText.includes("return createRequire(import.meta.url)(id);")) {
  inputFileText = inputFileText.replace(
    "return import.meta.require(id);",
    "return createRequire(import.meta.url)(id);"
  );
}

await Bun.write(outputFile, inputFileText);
@Dugnist Dugnist added the bug Something isn't working label Sep 18, 2023
@Electroid Electroid added the bundler Something to do with the bundler label Sep 18, 2023
@Zorato
Copy link

Zorato commented Sep 19, 2023

Got the same issue, tmp solution works!

@mbklein
Copy link

mbklein commented Sep 22, 2023

I managed to turn @Dugnist's temp solution into one that works on both regular and minified output by inserting this line at the top of the output instead:

import { createRequire as createImportMetaRequire } from "module"; import.meta.require ||= (id) => createImportMetaRequire(import.meta.url)(id);

It's essentially a polyfill for the missing import.meta.require.

@smt7174
Copy link

smt7174 commented Sep 25, 2023

Adding to @Dugnist and @mbklein 's solutions, I managed to read and write files by stream so that builds do not fail even if the file size is large.
(If built file size is too large, build sometimes fails)

// original built file
const inputFile = fs.createReadStream(pathToBuildedFile, {
  encoding: "utf-8"
});
// temp file 
const outputFile = fs.createWriteStream(`${pathToBuildedFile}.bak`, {
  encoding: "utf-8"
});

outputFile.write('import { createRequire as createImportMetaRequire } from "module"; import.meta.require ||= (id) => createImportMetaRequire(import.meta.url)(id);\n\n');

const decoder = new TextDecoder();
const transformer = new Transform({
  transform(
    chunk: Uint8Array, 
    encoding: string, 
    done: TransformCallback
  ): void {
    this.push(decoder.decode(chunk)) // convert Uint8Array to string
    done()
  },
})

inputFile.pipe(transformer).pipe(outputFile);

// delete original build file and rename temp file to original built file name 
fs.unlinkSync(pathToBuildedFile);
fs.renameSync(`${pathToBuildedFile}.bak`, pathToBuildedFile);

acheong08 pushed a commit to acheong08/obi-sync-lib that referenced this issue Sep 26, 2023
@mathiasrw
Copy link
Contributor

@Electroid
Copy link
Contributor

Duplicate of #6168

@Electroid Electroid marked this as a duplicate of #6168 Oct 28, 2023
@Electroid Electroid closed this as not planned Won't fix, can't repro, duplicate, stale Oct 28, 2023
@paperdave paperdave added enhancement New feature or request bug Something isn't working and removed bug Something isn't working enhancement New feature or request labels Mar 14, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working bundler Something to do with the bundler
Projects
None yet
Development

No branches or pull requests

7 participants