Skip to content

Commit

Permalink
feat: support to use import.meta.url on commonjs (#1)
Browse files Browse the repository at this point in the history
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

- **New Features**
- Introduced a new GitHub Actions workflow to publish on any commit or
pull request.
  - Added a function to handle `import.meta.url` in CommonJS modules.

- **Improvements**
  - Updated Node.js versions in workflows to include v22.
- Enhanced `package.json` with updated paths for imports, exports, and
types.
- Improved file system operations and path handling within the project.
- Updated TypeScript configurations for better code consistency and
module handling.

- **Bug Fixes**
- Addressed a `SyntaxError` related to `import.meta.url` in CommonJS
modules.

- **Documentation**
- Updated README with new instructions for auto-setting `package.json`.

- **Tests**
- Expanded test scenarios with additional asynchronous calls and
configurations.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
  • Loading branch information
fengmk2 authored Jul 7, 2024
1 parent 0d739a5 commit 155cb48
Show file tree
Hide file tree
Showing 10 changed files with 132 additions and 6 deletions.
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"
},
"require": {
"source": "./src/index.ts",
"types": "./dist/commonjs/index.d.ts",
"default": "./dist/commonjs/index.js"
}
}
}
},
"main": "./dist/commonjs/index.js",
"types": "./dist/commonjs/index.d.ts",
"module": "./dist/esm/index.js"
}
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

0 comments on commit 155cb48

Please sign in to comment.