Skip to content

Commit

Permalink
Merge pull request #14 from vite-plugin/v0.5.3
Browse files Browse the repository at this point in the history
V0.5.3
  • Loading branch information
caoxiemeihao authored Oct 16, 2022
2 parents b75afd4 + 66d44d1 commit 6530955
Show file tree
Hide file tree
Showing 19 changed files with 166 additions and 227 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -108,3 +108,6 @@ dist
package-lock.json
pnpm-lock.yaml
yarn.lock

/index.cjs
/index.js
14 changes: 14 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,17 @@
## 0.5.3 (2022-10-16)

- ee0a882 `src-output` -> `__snapshots__`
- 16593ff v0.5.3
- 2a5752b docs: v0.5.3
- 236730a refactor: use vite-plugin-utils
- bb793a5 chore: update config
- 1148671 feat: support `"type": "module"`
- f590da1 chore: `"strict": true`
- cf98458 bump deps
- 04f95f7 chore: bump deps
- 0434172 chore: update comments

---

## [2022-05-04] v0.3.0

Expand Down
3 changes: 1 addition & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,10 @@ export default {
}
```

## API
## API <sub><sup>(Define)</sup></sub>

```ts
export interface Options {
extensions?: string[]
filter?: (id: string) => false | undefined
dynamic?: {
/**
Expand Down
3 changes: 1 addition & 2 deletions README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,10 @@ export default {
}
```

## API
## API <sub><sup>(Define)</sup></sub>

```ts
export interface Options {
extensions?: string[]
filter?: (id: string) => false | undefined
dynamic?: {
/**
Expand Down
34 changes: 23 additions & 11 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,27 +1,37 @@
{
"name": "vite-plugin-commonjs",
"version": "0.5.2",
"version": "0.5.3",
"description": "A pure JavaScript implementation of CommonJs",
"main": "dist/index.js",
"type": "module",
"main": "index.js",
"types": "src",
"exports": {
".": {
"import": "./index.js",
"require": "./index.cjs"
}
},
"repository": {
"type": "git",
"url": "git+https://github.com/vite-plugin/vite-plugin-commonjs.git"
},
"author": "草鞋没号 <308487730@qq.com>",
"license": "MIT",
"scripts": {
"build": "rm -rf dist && tsc",
"prepublishOnly": "npm run build",
"test": "vite -c test/vite.config.ts"
"dev": "vite build --watch",
"build": "vite build",
"test": "vite -c test/vite.config.ts",
"prepublishOnly": "npm run build"
},
"dependencies": {
"fast-glob": "^3.2.11",
"vite-plugin-dynamic-import": "^0.9.9"
"fast-glob": "~3.2.11"
},
"devDependencies": {
"@types/node": "^17.0.36",
"typescript": "^4.7.2",
"vite": "^3.0.0-alpha.11"
"@types/node": "^18.7.14",
"typescript": "^4.7.4",
"vite": "^3.2.0-beta.2",
"vite-plugin-dynamic-import": "^1.2.3",
"vite-plugin-utils": "^0.3.3"
},
"keywords": [
"vite",
Expand All @@ -30,6 +40,8 @@
"require"
],
"files": [
"dist"
"src",
"index.cjs",
"index.js"
]
}
10 changes: 5 additions & 5 deletions src/analyze.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { AcornNode } from './types'
import { simpleWalk } from './utils'
import type { AcornNode } from './types'
import { walk } from 'vite-plugin-utils/function'

// ①(🎯): Top-level scope statement types, it also means statements that can be converted
// 顶级作用于语句类型,这种可以被无缝换成 import
Expand Down Expand Up @@ -56,7 +56,7 @@ export function analyzer(ast: AcornNode, code: string, id: string): Analyzed {
exports: [],
}

simpleWalk(ast, {
walk.sync(ast, {
CallExpression(node, ancestors) {
if (node.callee.name !== 'require') return

Expand All @@ -71,7 +71,7 @@ export function analyzer(ast: AcornNode, code: string, id: string): Analyzed {
dynamic: checkDynamicId(node),
})
},
AssignmentExpression(node, ancestors) {
AssignmentExpression(node) {
if (node.left.type !== 'MemberExpression') return
if (!(node.left.object.type === 'Identifier' && ['module', 'exports'].includes(node.left.object.name))) return

Expand Down Expand Up @@ -109,7 +109,7 @@ function checkDynamicId(node: AcornNode): RequireStatement['dynamic'] {
//
// Will be return nearset scope ancestor node (🎯-①)
// 这将返回最近作用域的祖先节点
function findTopLevelScope(ancestors: AcornNode[]): AcornNode {
function findTopLevelScope(ancestors: AcornNode[]): AcornNode | undefined {
const ances = ancestors.map(an => an.type).join()
const arr = [...ancestors].reverse()

Expand Down
69 changes: 36 additions & 33 deletions src/dynamic-require.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,18 @@
import path from 'path'
import path from 'node:path'
import type { ResolvedConfig } from 'vite'
import fastGlob from 'fast-glob'
import {
type Resolved,
dynamicImportToGlob,
Resolve,
utils,
dynamicImportToGlob,
mappingPath,
toLooseGlob,
} from 'vite-plugin-dynamic-import'
import fastGlob from 'fast-glob'
import { normalizePath, relativeify } from 'vite-plugin-utils/function'
import type { Options } from '.'
import type { Analyzed } from './analyze'
import { AcornNode } from './types'

const {
normallyImporteeRE,
tryFixGlobSlash,
toDepthGlob,
mappingPath,
} = utils
import type { AcornNode } from './types'
import { normallyImporteeRE } from './utils'

export interface DynamicRequireRecord {
node: AcornNode
Expand All @@ -33,7 +29,7 @@ export class DynaimcRequire {

constructor(
private config: ResolvedConfig,
private options: Options,
private options: Options & { extensions: string[] },
private resolve = new Resolve(config),
) { }

Expand All @@ -53,15 +49,15 @@ export class DynaimcRequire {
analyzed.code,
analyzed.id,
this.resolve,
options.extensions!,
this.options.extensions,
options.dynamic?.loose !== false,
)
if (!globResult) continue
const record: DynamicRequireRecord = { node }

let { files, resolved, normally } = globResult
// skip itself
files = files.filter(f => path.join(path.dirname(id), f) !== id)
files = files!.filter(f => normalizePath(path.join(path.dirname(id), f)) !== id)
// execute the dynamic.onFiles
options.dynamic?.onFiles && (files = options.dynamic?.onFiles(files, id) || files)

Expand All @@ -72,7 +68,10 @@ export class DynaimcRequire {

if (!files?.length) continue

const maps = mappingPath(files, resolved)
const maps = mappingPath(
files,
resolved ? { [resolved.alias.relative]: resolved.alias.findString } : undefined,
)
let counter2 = 0
record.dynaimc = {
importee: [],
Expand Down Expand Up @@ -124,15 +123,15 @@ async function globFiles(
resolved?: Resolved
/** After `expressiontoglob()` processing, it may become a normally path */
normally?: string
}> {
} | undefined> {
let files: string[]
let resolved: Resolved
let resolved: Resolved | undefined
let normally: string

const PAHT_FILL = '####/'
const EXT_FILL = '.extension'
let glob: string
let globRaw: string
let glob: string | null
let globRaw!: string

glob = await dynamicImportToGlob(
node.arguments[0],
Expand Down Expand Up @@ -162,21 +161,25 @@ async function globFiles(
return
}

glob = tryFixGlobSlash(glob)
loose !== false && (glob = toDepthGlob(glob))
glob.includes(PAHT_FILL) && (glob = glob.replace(PAHT_FILL, ''))
glob.endsWith(EXT_FILL) && (glob = glob.replace(EXT_FILL, ''))

const fileGlob = path.extname(glob)
? glob
// If not ext is not specified, fill necessary extensions
// e.g.
// `./foo/*` -> `./foo/*.{js,ts,vue,...}`
: glob + `.{${extensions.map(e => e.replace(/^\./, '')).join(',')}}`
// @ts-ignore
const globs = [].concat(loose ? toLooseGlob(glob) : glob)
.map((g: any) => {
g.includes(PAHT_FILL) && (g = g.replace(PAHT_FILL, ''))
g.endsWith(EXT_FILL) && (g = g.replace(EXT_FILL, ''))
return g
})
const fileGlobs = globs
.map(g => path.extname(g)
? g
// If not ext is not specified, fill necessary extensions
// e.g.
// `./foo/*` -> `./foo/*.{js,ts,vue,...}`
: g + `.{${extensions.map(e => e.replace(/^\./, '')).join(',')}}`
)

files = fastGlob
.sync(fileGlob, { cwd: /* 🚧-① */path.dirname(importer) })
.map(file => !file.startsWith('.') ? /* 🚧-② */`./${file}` : file)
.sync(fileGlobs, { cwd: /* 🚧-① */path.dirname(importer) })
.map(file => relativeify(file))

return { files, resolved }
}
8 changes: 4 additions & 4 deletions src/generate-export.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Analyzed } from './analyze'

export interface ExportsRuntime {
polyfill: string
exportDeclaration: string
exportDeclaration: string
}

export function generateExport(analyzed: Analyzed): ExportsRuntime | null {
Expand All @@ -11,16 +11,16 @@ export function generateExport(analyzed: Analyzed): ExportsRuntime | null {
}

const memberDefault = analyzed.exports
// Find `module.exports` or `exports.default`
.find(exp => exp.token.left === 'module' || exp.token.right === 'default')
// Find `module.exports` or `exports.default`
.find(exp => exp.token.left === 'module' || exp.token.right === 'default')

let members = analyzed.exports
// Exclude `module.exports` and `exports.default`
.filter(exp => exp.token.left !== 'module' && exp.token.right !== 'default')
.map(exp => exp.token.right)
// Remove duplicate export
members = [...new Set(members)]

const membersDeclaration = members.map(
m => `const __CJS__export_${m}__ = (module.exports == null ? {} : module.exports).${m}`,
)
Expand Down
10 changes: 5 additions & 5 deletions src/generate-import.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,14 +48,14 @@ export function generateImport(analyzed: Analyzed) {
topScopeNode,
dynamic,
} = req

// ③(🚧)
// Processed in dynamic-require.ts
if (dynamic === 'dynamic') continue

const impt: ImportRecord = { node, topScopeNode }
const importName = `__CJS__import__${count++}__`

const requireIdNode = node.arguments[0]
let requireId: string
if (!requireIdNode) continue // Not value - require()
Expand All @@ -65,13 +65,13 @@ export function generateImport(analyzed: Analyzed) {
requireId = requireIdNode.quasis[0].value.raw
}

if (!requireId) {
if (!requireId!) {
const codeSnippets = analyzed.code.slice(node.start, node.end)
throw new Error(`The following require statement cannot be converted.
-> ${codeSnippets}
${'^'.repeat(codeSnippets.length)}`)
}

if (topScopeNode) {
// ①(🎯)

Expand Down Expand Up @@ -113,7 +113,7 @@ export function generateImport(analyzed: Analyzed) {
impt.importee = `import { ${LV_str('as')} } from '${requireId}'`
}
} else if (init.type === 'MemberExpression') {
const onlyOneMember = ancestors.find(an => an.type === 'MemberExpression').property.name
const onlyOneMember = ancestors.find(an => an.type === 'MemberExpression')?.property.name
const importDefault = onlyOneMember === 'default'
if (typeof LV === 'string') {
if (importDefault) {
Expand Down
Loading

0 comments on commit 6530955

Please sign in to comment.