Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
barhun committed Apr 8, 2023
0 parents commit cd19109
Show file tree
Hide file tree
Showing 21 changed files with 291 additions and 0 deletions.
34 changes: 34 additions & 0 deletions .github/workflows/npm-publish.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# This workflow will run tests using node and then publish a package to npm when the branch 'main' receives a push.
# For more information see: https://docs.github.com/en/actions/publishing-packages/publishing-nodejs-packages

name: Publish to npm

on:
push:
branches: [main]
workflow_dispatch:

jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: 19
- run: npm ci
- run: npm test

publish-npm:
needs: test
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: 19
registry-url: https://registry.npmjs.org/
- run: npm ci
- run: npm publish
env:
NODE_AUTH_TOKEN: ${{secrets.npm_token}}
2 changes: 2 additions & 0 deletions .npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
.github
test
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2022 Burhan Del Rey

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
95 changes: 95 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
Node.js loader for import specifiers as file paths without extensions or as directory paths

 

Install:

```
npm i extensionless
```

 

Start `node` with the following flag added:

```
--experimental-loader=extensionless
```

 

You can now use import specifiers as file paths without extensions or as directory paths:

```js
// imports from the first existing file in the candidates list as follows

import mod from './mod'
// ['./mod.js', './mod/index.js']

import mod from '../mod' assert {type: 'json'}
// ['../mod.json', '../mod/index.json']

import api from '/apps/api'
// ['/apps/api.js', '/apps/api/index.js']

import web from 'file:///apps/web'
// ['file:///apps/web.js', 'file:///apps/web/index.js']
```

 

To configure this module, add the field `extensionless` to your project's `package.json`:

```json
"extensionless": {
"lookFor": ["js", "mjs", "cjs"]
}
```

| Field | Default Value |
| --------- | ------------- |
| `lookFor` | `["js"]` |

 

When it can be deduced from the specifier that its target is a directory, the resolver looks for only the index files:

```js
// imports from the first existing file in the candidates list as follows

import cur from '.'
// ['./index.js']

import up from '..'
// ['../index.js']

import mod from './mod/'
// ['./mod/index.js']

import mod from '../mod/' assert {type: 'json'}
// ['../mod/index.json']

import api from '/apps/api/'
// ['/apps/api/index.js']

import web from 'file:///apps/web/'
// ['file:///apps/web/index.js']
```

 

This loader also adds support for Windows path resolution with which you can use forward or backward slashes as separators.

```js
import mod from '.\\mod'
// ['./mod.js', './mod/index.js']

import mod from '..\\mod\\' assert {type: 'json'}
// ['../mod/index.json']

import api from 'C:/apps/api'
// ['/C:/apps/api.js', '/C:/apps/api/index.js']

import web from 'C:\\apps\\web\\'
// ['/C:/apps/web/index.js']
```
13 changes: 13 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

22 changes: 22 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"name": "extensionless",
"version": "1.4.5",
"type": "module",
"main": "src/index.js",
"license": "MIT",
"description": "Node.js loader for import specifiers as file paths without extensions or as directory paths",
"keywords": [
"node", "nodejs",
"module", "loader", "resolver", "resolution",
"esm", "es6", "esnext", "ecmascript",
"extension", "filename", "directory", "path"
],
"homepage": "https://github.com/barhun/extensionless#readme",
"repository": {
"type": "git",
"url": "git+https://github.com/barhun/extensionless.git"
},
"scripts": {
"test": "node --experimental-loader=./src/index.js test"
}
}
33 changes: 33 additions & 0 deletions src/config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import {readFile} from 'fs/promises'
import {dirname, isAbsolute, join} from 'path'
import {argv, cwd} from 'process'

let pkgJson = await (async () => {
let curDir, upDir = isAbsolute(argv[1] ?? '') ? argv[1] : cwd()

do {
try {
return JSON.parse(await readFile(join(curDir = upDir, 'package.json'), 'utf8'))
} catch (e) {
if (!['ENOTDIR', 'ENOENT', 'EISDIR'].includes(e.code)) {
throw new Error('Cannot retrieve package.json', {cause: e})
}
}
} while (curDir !== (upDir = dirname(curDir)))
})()

let warn = (field, desc) => console.warn('⚠️ \x1b[33m%s\x1b[0m', `Warning: The package.json field 'extensionless.${field}' must be ${desc}! Using the default value instead...`)

let defaults = {
lookFor: ['js']
}, {
lookFor
} = {...defaults, ...pkgJson?.extensionless}

Array.isArray(lookFor) && lookFor.length && lookFor.every(a => typeof a === 'string' && /^[a-z]+\w*$/i.test(a)) || (
lookFor = defaults.lookFor, warn('lookFor', 'an array of alphanumeric strings')
)

export {
lookFor
}
27 changes: 27 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import {extname, isAbsolute} from 'path'
import {lookFor} from './config.js'

let indexFiles = [lookFor.map(e => `index.${e}`), ['index.json']]
let candidates = indexFiles.map(i => i.map(f => extname(f)).concat(i.map(f => `/${f}`)))

let relSpecs = ['.', '..'], prefixes = ['./', '../', 'file://', '.\\', '..\\']
let extToSkip = ['.js', '.cjs', '.mjs', '.json', '.node', '.wasm'], empty = [[], []]

export async function resolve(specifier, {importAssertions, parentURL}, nextResolve) {
let isAbs = isAbsolute(specifier)

if (!isAbs && !relSpecs.includes(specifier) && !prefixes.some(p => specifier.startsWith(p))) {
return await nextResolve(specifier)
}

let selfURL = new URL((isAbs ? 'file://' : '') + specifier, parentURL).href
let postfixes = selfURL.endsWith('/') ? indexFiles : extToSkip.includes(extname(selfURL)) ? empty : candidates

for (let postfix of postfixes[+(importAssertions?.type === 'json')]) {
try {
return await nextResolve(selfURL + postfix)
} catch {}
}

return await nextResolve(selfURL)
}
Empty file added test/dir/ext/index.js/touch
Empty file.
1 change: 1 addition & 0 deletions test/dir/ext/index.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Date.now()
1 change: 1 addition & 0 deletions test/dir/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Date.now()
1 change: 1 addition & 0 deletions test/dir/index.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{}
1 change: 1 addition & 0 deletions test/dir/mod.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Date.now()
1 change: 1 addition & 0 deletions test/dir/mod.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{}
1 change: 1 addition & 0 deletions test/dir/mod/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
throw new Error(`This module shouldn't be imported`)
1 change: 1 addition & 0 deletions test/dir/mod/index.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"error": "This module shouldn't be imported"
2 changes: 2 additions & 0 deletions test/dir/sub/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
import '../mod'
import '../mod' assert {type: 'json'}
1 change: 1 addition & 0 deletions test/dir/sub/index.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{}
11 changes: 11 additions & 0 deletions test/dir/sub/rel.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import '.'
import '.' assert {type: 'json'}

import './'
import './' assert {type: 'json'}

import '..'
import '..' assert {type: 'json'}

import '../'
import '../' assert {type: 'json'}
17 changes: 17 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import './dir'
import './dir' assert {type: 'json'}

import './dir/'
import './dir/' assert {type: 'json'}

import './dir/index'
import './dir/index' assert {type: 'json'}

import './dir/index.js'
import './dir/index.json' assert {type: 'json'}

import './dir/ext'

import './dir/sub/rel'

console.log('✅ \x1b[32m%s\x1b[0m', 'Loaded all the modules successfully.')
6 changes: 6 additions & 0 deletions test/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"type": "module",
"extensionless": {
"lookFor": ["js", "mjs"]
}
}

0 comments on commit cd19109

Please sign in to comment.