-
Notifications
You must be signed in to change notification settings - Fork 78
feat: enhance config #49
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
Merged
Merged
Changes from all commits
Commits
Show all changes
22 commits
Select commit
Hold shift + click to select a range
34ece1b
fix: ts types
ClarkXia 8b9a816
fix: test case
ClarkXia 3d6c1fc
fix: prettier code
ClarkXia b84147e
feat: refactor context
ClarkXia 8a03ea6
feat: support class extends
ClarkXia 59861b4
fix: named export
ClarkXia 0780847
fix: extends class
ClarkXia 3c3bfec
fix: export api
ClarkXia 1e738b2
fix: add export of Context
ClarkXia 647bb9e
fix: ts type
ClarkXia f60b5aa
fix: compatible with camelCase
ClarkXia 5da9ac9
fix: export apis
ClarkXia 1ca544c
fix: export apis
ClarkXia 377bfd8
feat: support config write with ts/esm
ClarkXia a807bba
feat: enhance modifyUserConfig by config path
ClarkXia 9fd8d95
fix: ts type
ClarkXia 6c996d8
fix: get command module
ClarkXia 4b37f4e
fix: remove peerDependencies while build without webpack
ClarkXia 8985b94
fix: delete temp file when error occur
ClarkXia 9e510ff
feat: enhance modifyUserConfig
ClarkXia c6455f3
Merge branch 'release-next' into feat-enhance-config
ClarkXia c98d66e
chore: version
ClarkXia 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 hidden or 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 hidden or 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 hidden or 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,56 @@ | ||
| import * as path from 'path'; | ||
| import * as fs from 'fs'; | ||
| import { build as esbuild, Plugin} from 'esbuild'; | ||
|
|
||
| const buildConfig = async (fileName: string, mjs: boolean): Promise<string> => { | ||
| const pluginExternalDeps: Plugin = { | ||
| name: 'plugin-external-deps', | ||
| setup(build) { | ||
| build.onResolve({ filter: /.*/ }, (args) => { | ||
| const id = args.path; | ||
| if (id[0] !== '.' && !path.isAbsolute(id)) { | ||
| return { | ||
| external: true, | ||
| }; | ||
| } | ||
| }); | ||
| }, | ||
| }; | ||
| const pluginReplaceImport: Plugin = { | ||
| name: 'plugin-replace-import-meta', | ||
| setup(build) { | ||
| build.onLoad({ filter: /\.[jt]s$/ }, (args) => { | ||
| const contents = fs.readFileSync(args.path, 'utf8'); | ||
| return { | ||
| loader: args.path.endsWith('.ts') ? 'ts' : 'js', | ||
| contents: contents | ||
| .replace( | ||
| /\bimport\.meta\.url\b/g, | ||
| JSON.stringify(`file://${args.path}`), | ||
| ) | ||
| .replace( | ||
| /\b__dirname\b/g, | ||
| JSON.stringify(path.dirname(args.path)), | ||
| ) | ||
| .replace(/\b__filename\b/g, JSON.stringify(args.path)), | ||
| }; | ||
| }); | ||
| }, | ||
| }; | ||
|
|
||
| const result = await esbuild({ | ||
| entryPoints: [fileName], | ||
| outfile: 'out.js', | ||
| write: false, | ||
| platform: 'node', | ||
| bundle: true, | ||
| format: mjs ? 'esm' : 'cjs', | ||
| metafile: true, | ||
| plugins: [pluginExternalDeps, pluginReplaceImport], | ||
| }); | ||
| const { text } = result.outputFiles[0]; | ||
|
|
||
| return text; | ||
| }; | ||
|
|
||
| export default buildConfig; |
This file contains hidden or 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,94 @@ | ||
| import * as path from 'path'; | ||
| import * as fs from 'fs'; | ||
| import { Logger } from 'npmlog'; | ||
| import buildConfig from './buildConfig'; | ||
| import JSON5 = require('json5'); | ||
|
|
||
| interface INodeModuleWithCompile extends NodeModule { | ||
| _compile(code: string, filename: string): any; | ||
| } | ||
|
|
||
| async function loadConfig<T>(filePath: string, log: Logger): Promise<T|undefined> { | ||
| const start = Date.now(); | ||
| const isJson = filePath.endsWith('.json'); | ||
| const isTS = filePath.endsWith('.ts'); | ||
| const isMjs = filePath.endsWith('.mjs'); | ||
|
|
||
| let userConfig: T | undefined; | ||
|
|
||
| if (isJson) { | ||
| return JSON5.parse(fs.readFileSync(filePath, 'utf8')); | ||
| } | ||
|
|
||
| if (isMjs) { | ||
| const fileUrl = require('url').pathToFileURL(filePath); | ||
| if (isTS) { | ||
| // if config file is a typescript file | ||
| // transform config first, write it to disk | ||
| // load it with native Node ESM | ||
| const code = await buildConfig(filePath, true); | ||
| const tempFile = `${filePath}.js`; | ||
| fs.writeFileSync(tempFile, code); | ||
| try { | ||
| // eslint-disable-next-line no-eval | ||
| userConfig = (await eval(`import(tempFile + '?t=${Date.now()}')`)).default; | ||
| } catch(err) { | ||
| fs.unlinkSync(tempFile); | ||
| throw err; | ||
| } | ||
| // delete the file after eval | ||
| fs.unlinkSync(tempFile); | ||
| log.verbose('[config]',`TS + native esm module loaded in ${Date.now() - start}ms, ${fileUrl}`); | ||
| } else { | ||
| // eslint-disable-next-line no-eval | ||
| userConfig = (await eval(`import(fileUrl + '?t=${Date.now()}')`)).default; | ||
| log.verbose('[config]',`native esm config loaded in ${Date.now() - start}ms, ${fileUrl}`); | ||
| } | ||
| } | ||
|
|
||
| if (!userConfig && !isTS && !isMjs) { | ||
| // try to load config as cjs module | ||
| try { | ||
| delete require.cache[require.resolve(filePath)]; | ||
| userConfig = require(filePath); | ||
| log.verbose('[config]', `cjs module loaded in ${Date.now() - start}ms`); | ||
| } catch (e) { | ||
| const ignored = new RegExp( | ||
| [ | ||
| `Cannot use import statement`, | ||
| `Must use import to load ES Module`, | ||
| // #1635, #2050 some Node 12.x versions don't have esm detection | ||
| // so it throws normal syntax errors when encountering esm syntax | ||
| `Unexpected token`, | ||
| `Unexpected identifier`, | ||
| ].join('|'), | ||
| ); | ||
| if (!ignored.test(e.message)) { | ||
| throw e; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| if (!userConfig) { | ||
| // if cjs module load failed, the config file is ts or using es import syntax | ||
| // bundle config with cjs format | ||
| const code = await buildConfig(filePath, false); | ||
| const tempFile = `${filePath}.js`; | ||
| fs.writeFileSync(tempFile, code); | ||
| delete require.cache[require.resolve(tempFile)]; | ||
| try { | ||
| // eslint-disable-next-line @typescript-eslint/no-var-requires | ||
| const raw = require(tempFile); | ||
| // eslint-disable-next-line no-underscore-dangle | ||
| userConfig = raw.__esModule ? raw.default : raw; | ||
| } catch (err) { | ||
| fs.unlinkSync(tempFile); | ||
| throw err; | ||
| } | ||
| fs.unlinkSync(tempFile); | ||
| log.verbose('[config]', `bundled module file loaded in ${Date.now() - start}m`); | ||
| } | ||
| return userConfig; | ||
| } | ||
|
|
||
| export default loadConfig; |
This file contains hidden or 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 @@ | ||
| const path = require('path'); | ||
|
|
||
| module.exports = { | ||
| entry: path.join('src', 'config.js'), | ||
| }; |
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.
注释是不是加代码上面更好点