如何mypkg.config.ts從我基于 ESM 構建的 npm 模塊中的專案根目錄讀取組態檔(例如)?
我發現了這個,并想出了如何.json為.ts.
uj5u.com熱心網友回復:
經過幾個小時的搜索,我在 vite 的資源中找到了我需要的東西。
您所要做的就是使用 esbuild 將您的組態檔轉換為 js,然后使用
const config = await import(`file://${absolutePathToTranspiledConfig}`)
然后只需洗掉生成的js檔案。
編輯: 特別是 `vite' 使用以下轉譯腳本:
await build({
entryPoints: [/*path to config with .ts extension*/],
bundle: true,
minify: true,
platform: 'node',
outfile: /*path to transpiled config*/,
sourcemap: 'inline',
metafile: true,
format: 'esm',
plugins: [
{
name: 'externalize-deps',
setup(build) {
build.onResolve({ filter: /.*/ }, args => {
const id = args.path
if (id[0] !== '.' && !path.isAbsolute(id)) {
return {
external: true
}
}
})
}
},
{
name: 'replace-import-meta',
setup(build) {
build.onLoad({ filter: /\.[jt]s$/ }, async args => {
const contents = await fs.readFile(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))
}
})
}
}
]
})
但是,我在這里無法理解這些插件的含義
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/436846.html
