Skip to content

Commit

Permalink
Improve(Cross Import): Bundle jiti and sucrase to improve stability
Browse files Browse the repository at this point in the history
  • Loading branch information
1aron committed Jun 14, 2023
1 parent 79e4ea4 commit 1ab845b
Show file tree
Hide file tree
Showing 8 changed files with 361 additions and 482 deletions.
729 changes: 320 additions & 409 deletions package-lock.json

Large diffs are not rendered by default.

23 changes: 1 addition & 22 deletions packages/cross-import/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,10 +68,7 @@ import crossImport from 'cross-import'
```

```ts
crossImport(
source: string | fg.Pattern[],
options?: fg.Options
): any
crossImport(modulePath: string): any
```

### Import `.ts` in `.js`
Expand All @@ -92,24 +89,6 @@ export const bar = 'bar'
crossImport('./foo.ts')
// {"bar": "bar", "foo": "foo"}
```
And so on...

### Import format-multiple JS config
This is often used to read various user-defined configuration files like `master.css.ts`, `next.config.js`, `vite.config.mjs` ...

`index.js`
```js
crossImport('master.css.{js,ts,cjs,mjs}')
// {"bar": "bar", "foo": "foo"}
```

## Options
Inherited from [fast-glob options](https://github.com/mrmlnc/fast-glob#options-3)
```js
{
cwd: process.cwd()
}
```

<br>

Expand Down
9 changes: 3 additions & 6 deletions packages/cross-import/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "cross-import",
"scripts": {
"build:cjs": "esbuild src/index.ts --bundle --outfile=dist/index.js --format=cjs --minify --sourcemap --platform=node --external:esbuild --external:fast-glob --external:jiti --external:@techor/extend --external:sucrase --external:upath",
"build:cjs": "esbuild src/index.ts --bundle --outfile=dist/index.js --format=cjs --minify --sourcemap --platform=node",
"build:type": "tsc --emitDeclarationOnly --preserveWatchOutput",
"build": "npm run build:cjs && npm run build:type",
"dev": "conc 'npm:build:* -- --watch'",
Expand Down Expand Up @@ -54,11 +54,8 @@
"files": [
"dist"
],
"dependencies": {
"@techor/extend": "",
"fast-glob": "^3.2.12",
"jiti": "^1.18.2",
"devDependencies": {
"sucrase": "^3.32.0",
"upath": "^2.0.1"
"jiti": "^1.18.2"
}
}
57 changes: 24 additions & 33 deletions packages/cross-import/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,15 @@
import path from 'path'
import fg from 'fast-glob'
import extend from '@techor/extend'
import jiti from 'jiti'
import jiti from 'jiti/dist/jiti'
import { transform } from 'sucrase'

export default function crossImport(
source: string | fg.Pattern[],
options?: fg.Options
): any {
options = extend({ cwd: process.cwd() }, options)
if (!source) return
const filePath = fg.sync(source, options)[0]
if (!filePath) return
const resolvedFilePath = path.resolve(options.cwd, filePath)
export default function crossImport(modulePath: string): any {
if (!modulePath) return
if (process.env.DEBUG) {
console.log('[DEBUG: Cross Import] resolvedFilePath:', resolvedFilePath)
console.log('[DEBUG: Cross Import] modulePath:', modulePath)
}

/** try to delete cache first */
try {
if (require.cache[resolvedFilePath]) {
delete require.cache[resolvedFilePath]
if (require.cache[modulePath]) {
delete require.cache[modulePath]
if (process.env.DEBUG) {
console.log('[DEBUG: Cross Import] delete cache')
}
Expand All @@ -31,26 +20,28 @@ export default function crossImport(
if (process.env.DEBUG) {
console.log('[DEBUG: Cross Import] require')
}
return require(resolvedFilePath)
return require(modulePath)
} catch (error) {
if (process.env.DEBUG) {
console.log('[DEBUG: Cross Import] JITI')
console.error(error)
}
return jiti(__filename, {
interopDefault: true,
cache: false,
transform: (options) => {
if (process.env.DEBUG) {
console.log('[DEBUG: Cross Import] JITI transform')
console.error(error)
try {
return jiti(__filename, {
interopDefault: true,
cache: false,
transform: (options) => {
if (process.env.DEBUG) {
console.log('[DEBUG: Cross Import] JITI transform')
console.error(error)
}
return transform(options.source, {
transforms: ['imports', 'typescript'],
})
}
return transform(options.source, {
transforms: ['imports', 'typescript'],
})
}
})(resolvedFilePath)
})(modulePath)
} catch (error) {
throw new Error(error)
}
}
}

export { crossImport }
}
14 changes: 7 additions & 7 deletions packages/cross-import/tests/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@ import path from 'path'

it('import .ts in .js', () => {
expect(
crossImport('./foo.ts', { cwd: __dirname })
crossImport(path.resolve(__dirname, './foo.ts'))
).toEqual({ 'bar': 'bar', 'foo': 'foo' })
})

it('read config from file', () => {
expect(
crossImport('home-config.ts', { cwd: __dirname }))
crossImport(path.resolve(__dirname, 'home-config.ts')))
.toEqual({
'default': {
'classes': { 'btn': 'font:12' },
Expand All @@ -23,16 +23,16 @@ it('read config from file', () => {

it('read config with third-party deps', () => {
expect(
crossImport('external.ts', { cwd: __dirname }).default
crossImport(path.resolve(__dirname, 'external.ts')).default
)
.toBeDefined()
})

it('read non-existent file', () => {
expect(
crossImport('idontexist.ts', { cwd: __dirname })
)
.toBeUndefined()
expect(() => {
crossImport(path.resolve(__dirname, 'idontexist.ts'))
})
.toThrowError()
})

// Do not test secondary imports in a test environment, inaccurate.
5 changes: 3 additions & 2 deletions packages/explore-config/src/core.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import log from '@techor/log'
import type { Pattern } from 'fast-glob'
import { crossImport } from 'cross-import'
import crossImport from 'cross-import'
import extend from '@techor/extend'
import { exploreConfigPath } from './explore-config-path'
import upath from 'upath'

export default function exploreConfig(
sources: Pattern | Pattern[],
Expand All @@ -28,7 +29,7 @@ export default function exploreConfig(
try {
const foundPath = exploreConfigPath(sources, options)
if (foundPath) {
const foundConfigModule = crossImport(foundPath, { cwd })
const foundConfigModule = crossImport(upath.resolve(options.cwd, foundPath))
for (const key of keys) {
foundConfig = foundConfigModule[key]
if (foundConfig) {
Expand Down
4 changes: 2 additions & 2 deletions packages/pack/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ Simultaneously output `cjs`, `esm`, `iife`, `type declarations` respectively acc
{
"name": "a",
"scripts": {
"build": "tsx ../techor/src/bin pack",
"build": "ts-node ../techor/src/bin pack",
"dev": "npm run build -- --watch"
},
"main": "dist/cjs/index.js",
Expand Down Expand Up @@ -153,7 +153,7 @@ Packaging CSS is more straightforward, configuring `style` and `main` entry poin
{
"name": "b",
"scripts": {
"build": "tsx ../techor/src/bin pack",
"build": "ts-node ../techor/src/bin pack",
"dev": "npm run build -- --watch"
},
"main": "./dist/index.css",
Expand Down
2 changes: 1 addition & 1 deletion packages/techor/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ Typical workspace scripts for authoring a package:
```json
{
"scripts": {
"build": "tsx ../techor/src/bin pack",
"build": "ts-node ../techor/src/bin pack",
"dev": "npm run build -- --watch",
"test": "jest",
"type-check": "tsc --noEmit",
Expand Down

0 comments on commit 1ab845b

Please sign in to comment.