web-infra-dev / rslib

Create JavaScript libraries in a simple and intuitive way.
https://lib.rsbuild.dev/
MIT License
417 stars 21 forks source link

[Bug]: The Import Attributes of an external module will be removed #413

Open colinaaa opened 2 days ago

colinaaa commented 2 days ago

Version

System:
    OS: macOS 14.6.1
    CPU: (12) arm64 Apple M2 Max
    Memory: 49.81 GB / 96.00 GB
    Shell: 3.7.1 - /opt/homebrew/bin/fish
  Browsers:
    Chrome: 130.0.6723.117
    Safari: 17.6
  npmPackages:
    @rslib/core: ^0.0.17 => 0.0.17

Details

I'm using Rslib with Import Attributes.

import pkg from 'tailwindcss/package.json' with { type: 'json' }

If the imported JSON has been externalized, the Import Attributes will be removed:

// dist/index.js
import * as __WEBPACK_EXTERNAL_MODULE_tailwindcss_package_json__ from "tailwindcss/package.json";

This will give an error since we should use Import Attributes to import JSON in NodeJS ESM.

This is the same when using dynamic import:

import('tailwindcss/package.json', { with: { type: 'json' }}).then(({ default: pkg }) => {
  console.log('from dynamic import', pkg.version)
})
import("tailwindcss/package.json").then(({ default: pkg })=>{
    console.log('from dynamic import', pkg.version);
});

Reproduce link

https://github.com/colinaaa-reproductions/rslib-repro-import-attributes

Reproduce Steps

  1. pnpm install
  2. npm run build
  3. node dist/index.js

An error will be thrown:

node:internal/modules/esm/assert:89
        throw new ERR_IMPORT_ASSERTION_TYPE_MISSING(url, validType);
              ^

TypeError [ERR_IMPORT_ASSERTION_TYPE_MISSING]: Module "/root/node_modules/.pnpm/tailwindcss@3.4.14/node_modules/tailwindcss/package.json" needs an import attribute of type "json"
    at validateAttributes (node:internal/modules/esm/assert:89:15)
    at defaultLoad (node:internal/modules/esm/load:153:3)
    at async ModuleLoader.load (node:internal/modules/esm/loader:553:7)
    at async ModuleLoader.moduleProvider (node:internal/modules/esm/loader:434:45) {
  code: 'ERR_IMPORT_ASSERTION_TYPE_MISSING'
}

Node.js v20.17.0
colinaaa commented 2 days ago

The with: { type: 'json' } still exists after builtin:swc-loader:

Image