-
Notifications
You must be signed in to change notification settings - Fork 2
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
Node resolver: Refactor, add tests, and improve edge cases #159
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
9a931a2
Refactor, add tests, and improve resolution
calebeby d9a01c8
Use @types/node of lowest supported node version
calebeby c518d8c
Make TS happy
calebeby 9339736
Remove TODO
calebeby d0ce12e
Change "resolves main field" test to also check that main > index.js
calebeby File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
--- | ||
'pleasantest': patch | ||
--- | ||
|
||
Improve node_modules and relative paths resolution |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,118 @@ | ||
import type { Plugin, RollupCache } from 'rollup'; | ||
import { rollup } from 'rollup'; | ||
import { promises as fs } from 'fs'; | ||
import commonjs from '@rollup/plugin-commonjs'; | ||
import { processGlobalPlugin } from './plugins/process-global-plugin'; | ||
import * as esbuild from 'esbuild'; | ||
import { parse } from 'cjs-module-lexer'; | ||
// @ts-expect-error @types/node@12 doesn't like this import | ||
import { createRequire } from 'module'; | ||
import { isBareImport, npmPrefix } from './extensions-and-detection'; | ||
let npmCache: RollupCache | undefined; | ||
|
||
/** | ||
* Any package names in this set will need to have their named exports detected manually via require() | ||
* because the export names cannot be statically analyzed | ||
*/ | ||
const dynamicCJSModules = new Set(['prop-types', 'react-dom', 'react']); | ||
|
||
/** | ||
* Bundle am npm module entry path into a single file | ||
* @param mod The full path of the module to bundle, including subpackage/path | ||
* @param id The imported identifier | ||
* @param optimize Whether the bundle should be a minified/optimized bundle, or the default quick non-optimized bundle | ||
*/ | ||
export const bundleNpmModule = async ( | ||
mod: string, | ||
id: string, | ||
optimize: boolean, | ||
) => { | ||
let namedExports: string[] = []; | ||
if (dynamicCJSModules.has(id)) { | ||
let isValidCJS = true; | ||
try { | ||
const text = await fs.readFile(mod, 'utf8'); | ||
// Goal: Determine if it is ESM or CJS. | ||
// Try to parse it with cjs-module-lexer, if it fails, assume it is ESM | ||
// eslint-disable-next-line @cloudfour/typescript-eslint/await-thenable | ||
await parse(text); | ||
} catch { | ||
isValidCJS = false; | ||
} | ||
|
||
if (isValidCJS) { | ||
const require = createRequire(import.meta.url); | ||
// eslint-disable-next-line @cloudfour/typescript-eslint/no-var-requires | ||
const imported = require(mod); | ||
if (typeof imported === 'object' && !imported.__esModule) | ||
namedExports = Object.keys(imported); | ||
} | ||
} | ||
|
||
const virtualEntry = '\0virtualEntry'; | ||
const hasSyntheticNamedExports = namedExports.length > 0; | ||
const bundle = await rollup({ | ||
input: hasSyntheticNamedExports ? virtualEntry : mod, | ||
cache: npmCache, | ||
shimMissingExports: true, | ||
treeshake: true, | ||
preserveEntrySignatures: 'allow-extension', | ||
plugins: [ | ||
hasSyntheticNamedExports && | ||
({ | ||
// This plugin handles special-case packages whose named exports cannot be found via static analysis | ||
// For these packages, the package is require()'d, and the named exports are determined that way. | ||
// A virtual entry exports the named exports from the real entry package | ||
name: 'cjs-named-exports', | ||
resolveId(id) { | ||
if (id === virtualEntry) return virtualEntry; | ||
}, | ||
load(id) { | ||
if (id === virtualEntry) { | ||
const code = `export * from '${mod}' | ||
export {${namedExports.join(', ')}} from '${mod}' | ||
export { default } from '${mod}'`; | ||
return code; | ||
} | ||
}, | ||
} as Plugin), | ||
pluginNodeResolve(), | ||
processGlobalPlugin({ NODE_ENV: 'development' }), | ||
commonjs({ | ||
extensions: ['.js', '.cjs', ''], | ||
sourceMap: false, | ||
transformMixedEsModules: true, | ||
}), | ||
(optimize && { | ||
name: 'esbuild-minify', | ||
renderChunk: async (code) => { | ||
const output = await esbuild.transform(code, { | ||
minify: true, | ||
legalComments: 'none', | ||
}); | ||
return { code: output.code }; | ||
}, | ||
}) as Plugin, | ||
].filter(Boolean), | ||
}); | ||
npmCache = bundle.cache; | ||
const { output } = await bundle.generate({ | ||
format: 'es', | ||
indent: false, | ||
exports: 'named', | ||
preferConst: true, | ||
}); | ||
|
||
return output[0].code; | ||
}; | ||
|
||
const pluginNodeResolve = (): Plugin => { | ||
return { | ||
name: 'node-resolve', | ||
resolveId(id) { | ||
if (isBareImport(id)) return { id: npmPrefix + id, external: true }; | ||
// If requests already have the npm prefix, mark them as external | ||
if (id.startsWith(npmPrefix)) return { id, external: true }; | ||
}, | ||
}; | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
export const npmPrefix = '@npm/'; | ||
|
||
export const isRelativeOrAbsoluteImport = (id: string) => | ||
id === '.' || | ||
id === '..' || | ||
id.startsWith('./') || | ||
id.startsWith('../') || | ||
id.startsWith('/'); | ||
|
||
export const isBareImport = (id: string) => | ||
!( | ||
isRelativeOrAbsoluteImport(id) || | ||
id.startsWith('\0') || | ||
id.startsWith(npmPrefix) | ||
); | ||
|
||
export const cssExts = /\.(?:css|styl|stylus|s[ac]ss|less)$/; | ||
export const jsExts = /\.(?:[jt]sx?|[cm]js)$/; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Nothing in here has changed, it was just moved out of npm-plugin