tc39 / proposal-import-attributes

Proposal for syntax to import ES modules with assertions
https://tc39.es/proposal-import-attributes/
Apache License 2.0
569 stars 32 forks source link

Examples? #122

Open ArtemFrontendACTUM opened 2 years ago

ArtemFrontendACTUM commented 2 years ago

Sounds like redundant complication of ES standard. Could you provide some examples or repo for the problematics? Because the problem seems farfetched.

Delapouite commented 7 months ago

In their latest release, Bun decided to use an import attribute to interact with sqlite database:

import db from './my.db' with {type: "sqlite"};

const {id} = db
  .query("SELECT id FROM users LIMIT 1")
  .get();

console.log(id); // 1

https://bun.sh/blog/bun-v1.0.23

juner commented 5 months ago

check support sample.

  async function enableWithTypeSyntax([type, dataUrl, ok]) {
    let enableWithTypeSyntax = false;
    const option = (() => {
      const option = {};
      const w = {type};
      Reflect.defineProperty(option, "with", {
        get: () => (enableWithTypeSyntax=true,w),
      });
      return option;
    })();
    let result;
    try {
      const importMethod = new Function("dataUrl", "option", "return import(dataUrl, option);");
      result = await importMethod(dataUrl, option);
      if (!enableWithTypeSyntax) return [false, new Error("not with read.")];
      const isValid = typeof ok === "function" ? ok(result?.["default"], result) : !!ok;
      if (!isValid) return [false, new Error("type is invalid", {cause: {default: result?.default, module: result}})];
      return [true,"ok"];
    }catch(e){
      if (e instanceof SyntaxError) return [false, new Error("not supported. import attribute syntax", {cause:e})]
      return [false, e];
    }
  }

playground