Azure / azure-sdk-for-js

This repository is for active development of the Azure SDK for JavaScript (NodeJS & Browser). For consumers of the SDK we recommend visiting our public developer docs at https://docs.microsoft.com/javascript/azure/ or our versioned developer docs at https://azure.github.io/azure-sdk-for-js.
MIT License
1.98k stars 1.15k forks source link

ESM import of @azure/monitor-opentelemetry fails #28427

Open alexgagnon opened 5 months ago

alexgagnon commented 5 months ago

Describe the bug In a project using ESM ("type": "module") it seems like @azure/monitor-opentelemetry incorrectly references the underlying @opentelemetry/resource library, giving the following error:

var resources = require('@opentelemetry/resources');
                ^

Error [ERR_REQUIRE_ESM]: require() of ES Module C:\Users\...\node_modules\@opentelemetry\resources\build\src\index.js from C:\Users\...\node_modules\@azure\monitor-opentelemetry\dist\index.js not supported.
C:\Users\...\node_modules\@opentelemetry\resources\build\src\index.js is treated as an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which declares all .js files in that package scope as ES modules.
Instead either rename C:\Users\...\node_modules\@opentelemetry\resources\build\src\index.js to end in .cjs, change the requiring code to use dynamic import() which is available in all CommonJS modules, or change "type": "module" to "type": "commonjs" in C:\Users\...\node_modules\@opentelemetry\resources\package.json to treat all .js files as CommonJS (using .mjs for all ES modules instead).

    at Object.<anonymous> (C:\Users\...\node_modules\@azure\monitor-opentelemetry\dist\index.js:8:17) {
  code: 'ERR_REQUIRE_ESM'
}

To Reproduce Steps to reproduce the behavior:

  1. Create a simple node project with typescript and @azure/monitor-opentelemetry
  2. Import the useAzureMonitor function
import { useAzureMonitor } from '@azure/monitor-opentelemetry';
useAzureMonitor();

Expected behavior It works and starts sending data to the insights resource indicated in the APPLICATIONINSIGHTS_CONNECTION_STRING env var

Additional context

Here's my tsconfig.json file if that helps

{
  "compilerOptions": {
    "module": "NodeNext",
    "target": "ES2020",
    "lib": ["ES2020"],
    "skipLibCheck": true,
    "outDir": "dist",
    // "esModuleInterop": true,
    // "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "resolveJsonModule": true,
    "isolatedModules": true,

    /* Linting */
    "strict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noFallthroughCasesInSwitch": true,
  },
  "include": ["src"],
}
JacksonWeber commented 2 months ago

@alexgagnon I've recreated an application using the reproduction steps detailed in your issue (including the tsconfig.json) and I don't appear to have any errors thrown. Could you give this a try with the latest version of the @azure/monitor-opentelemetry package?