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

feat: support to use import.meta.url on commonjs #1

Merged
merged 1 commit into from
Jul 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/nodejs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,4 @@ jobs:
uses: node-modules/github-actions/.github/workflows/node-test.yml@master
with:
os: 'ubuntu-latest'
version: '16, 18, 20'
version: '16, 18, 20, 22'
23 changes: 23 additions & 0 deletions .github/workflows/pkg.pr.new.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
name: Publish Any Commit
on: [push, pull_request]

jobs:
build:
runs-on: ubuntu-latest

steps:
- name: Checkout code
uses: actions/checkout@v4

- run: corepack enable
- uses: actions/setup-node@v4
with:
node-version: 20

- name: Install dependencies
run: npm install

- name: Build
run: npm run prepublishOnly --if-present

- run: npx pkg-pr-new publish
2 changes: 0 additions & 2 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,3 @@ jobs:
secrets:
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
GIT_TOKEN: ${{ secrets.GIT_TOKEN }}
with:
checkTest: false
23 changes: 23 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,26 @@ Auto set package.json after [tshy](https://github.com/isaacs/tshy) run
## keep `types`

Set `package.types` to `package.exports['.'].require.types`

## Auto fix `import.meta.url` SyntaxError on CJS

```bash
SyntaxError: Cannot use 'import.meta' outside a module
```

e.g.: Get the file's dirname

```ts
// src/index.ts

import { fileURLToPath } from 'node:url';
import path from 'node:path';

export function getDirname() {
if (typeof __dirname !== 'undefined') {
return __dirname;
}
// @ts-ignore
return path.dirname(fileURLToPath(import.meta.url));
}
```
7 changes: 6 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,13 +43,18 @@
"./package.json": "./package.json",
".": {
"import": {
"source": "./src/index.ts",
"types": "./dist/esm/index.d.ts",
"default": "./dist/esm/index.js"
Comment on lines +46 to 48
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tip

Codebase Verification

The types file ./dist/esm/index.d.ts is missing.

Please ensure that the build process correctly generates the index.d.ts file in the ./dist/esm/ directory. Verify the build scripts and configurations related to type generation.

  • Check the build scripts in package.json or related configuration files.
  • Ensure the index.d.ts file is correctly generated and placed in the ./dist/esm/ directory.
Analysis chain

Verify the new import paths.

Ensure that the new import paths for source and types are correct and align with the project structure.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the new import paths in package.json.

# Test: Check if the source file exists. Expect: File should exist.
test -f ./src/index.ts && echo "Source file exists" || echo "Source file missing"

# Test: Check if the types file exists. Expect: File should exist.
test -f ./dist/esm/index.d.ts && echo "Types file exists" || echo "Types file missing"

Length of output: 150

},
"require": {
"source": "./src/index.ts",
"types": "./dist/commonjs/index.d.ts",
"default": "./dist/commonjs/index.js"
Comment on lines +51 to 53
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tip

Codebase Verification

Missing Type Declaration File

The index.d.ts file is missing because the main tsconfig.json does not have the necessary declaration and outDir settings. These settings are required to generate type declaration files.

  • File: tsconfig.json
    • Add "declaration": true and "outDir": "./dist/commonjs" to the compilerOptions.

Please update the tsconfig.json to include these settings to ensure type declaration files are generated correctly.

Analysis chain

Verify the new require paths.

Ensure that the new require paths for source and types are correct and align with the project structure.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the new require paths in package.json.

# Test: Check if the source file exists. Expect: File should exist.
test -f ./src/index.ts && echo "Source file exists" || echo "Source file missing"

# Test: Check if the types file exists. Expect: File should exist.
test -f ./dist/commonjs/index.d.ts && echo "Types file exists" || echo "Types file missing"

Length of output: 155


Script:

#!/bin/bash
# Description: Investigate the missing types file.

# Search for the index.d.ts file in the repository to see if it exists elsewhere.
fd -e d.ts index

# Check for relevant build configurations in the project.
fd -e json -e js -e tsconfig -e babelrc

Length of output: 205


Script:

#!/bin/bash
# Description: Display the contents of tsconfig.json to understand the configuration for type declaration files.

# Display the contents of tsconfig.json
cat tsconfig.json

Length of output: 396


Script:

#!/bin/bash
# Description: Search for other tsconfig.json files and check for declaration and outDir settings.

# Search for other tsconfig.json files in the repository.
fd -e json tsconfig

# Check for declaration and outDir settings in all tsconfig.json files.
fd -e json tsconfig | xargs -I {} sh -c 'echo "File: {}"; cat {} | jq ".compilerOptions.declaration, .compilerOptions.outDir"'

Length of output: 368

}
}
}
},
"main": "./dist/commonjs/index.js",
"types": "./dist/commonjs/index.d.ts",
"module": "./dist/esm/index.js"
Comment on lines +57 to +59
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tip

Codebase Verification

Paths in package.json are incorrect or the build process is failing.

The specified files in the main, types, and module fields do not exist. This could be due to incorrect paths or an issue with the build process. Please verify the build process and ensure the paths are correct.

  • ./dist/commonjs/index.js
  • ./dist/commonjs/index.d.ts
  • ./dist/esm/index.js
Analysis chain

Verify the updated paths.

Ensure that the updated paths for main, types, and module are correct and align with the project structure.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the updated paths in package.json.

# Test: Check if the main file exists. Expect: File should exist.
test -f ./dist/commonjs/index.js && echo "Main file exists" || echo "Main file missing"

# Test: Check if the types file exists. Expect: File should exist.
test -f ./dist/commonjs/index.d.ts && echo "Types file exists" || echo "Types file missing"

# Test: Check if the module file exists. Expect: File should exist.
test -f ./dist/esm/index.js && echo "Module file exists" || echo "Module file missing"

Length of output: 242

}
26 changes: 24 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,31 @@
#!/usr/bin/env node

import { writeFileSync, readFileSync } from 'node:fs'
import { writeFileSync, readFileSync, readdirSync, statSync } from 'node:fs'
import path from 'node:path'

const pkg = JSON.parse(readFileSync('package.json', 'utf-8'));
const cwd = process.cwd();

const pkg = JSON.parse(readFileSync(path.join(cwd, 'package.json'), 'utf-8'));
// make sure commonjs *.d.ts can import types
pkg.types = pkg.exports['.'].require.types;

writeFileSync('package.json', JSON.stringify(pkg, null, 2) + '\n')

// Replace all `import.meta.url` into 'import.meta.url' string placeholder on commonjs.
function replaceImportMetaUrl(baseDir: string) {
const names = readdirSync(baseDir);
for (const name of names) {
const filepath = path.join(baseDir, name);
const stat = statSync(filepath);
if (stat.isDirectory()) {
replaceImportMetaUrl(filepath);
continue;
}
if (!filepath.endsWith('.js')) {
continue;
}
writeFileSync(filepath, readFileSync(filepath, 'utf-8').replaceAll('import.meta.url', '"import_meta_url_placeholder_by_tshy_after"'));
console.log('Auto fix "import.meta.url" on %s', filepath);
}
}
replaceImportMetaUrl(path.join(cwd, 'dist/commonjs'));
10 changes: 10 additions & 0 deletions test/fixtures/demo/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { fileURLToPath } from 'node:url';
import path from 'node:path';

export function getDirname() {
if (typeof __dirname !== 'undefined') {
return __dirname;
}
// @ts-ignore
return path.dirname(fileURLToPath(import.meta.url));
}
16 changes: 16 additions & 0 deletions test/fixtures/demo/src/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"compilerOptions": {
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"inlineSources": true,
"jsx": "react",
"module": "nodenext",
"moduleResolution": "nodenext",
"noUncheckedIndexedAccess": true,
"resolveJsonModule": true,
"skipLibCheck": false,
"sourceMap": true,
"strict": true,
"target": "es2022"
}
}
18 changes: 18 additions & 0 deletions test/fixtures/demo/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"compilerOptions": {
"declaration": true,
"declarationMap": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"inlineSources": true,
"jsx": "react",
"module": "nodenext",
"moduleResolution": "nodenext",
"noUncheckedIndexedAccess": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"sourceMap": true,
"strict": true,
"target": "es2022"
}
}
11 changes: 11 additions & 0 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,21 @@ describe('test/index.test.ts', () => {
});

it('should work', async () => {
await coffee.spawn('tshy', { cwd })
.debug()
.expect('code', 0)
.end();
await coffee.fork(bin, { cwd })
.debug()
.expect('code', 0)
.end();
await coffee.spawn('node', [
'--require', './dist/commonjs/index.js',
'-p', '123123',
], { cwd })
.debug()
.expect('code', 0)
.end();
const pkg = JSON.parse(fs.readFileSync(packageFile, 'utf-8'));
assert.equal(pkg.types, './dist/commonjs/index.d.ts');
});
Expand Down
Loading