2021年6月26日土曜日

deno bundleコマンドで単一のJavaScriptファイルを作成する

すべての依存関係を含むJavaScriptファイルをコマンド一つでサクッと作れます。



deno bundle [URL]


先日、denoでTypeScriptをJavaScriptに変換するサンプルを投稿しましたが、以下のページにもっと簡単な方法が記載されていました…。
Deno Manual 9.4 Bundler



実行


deno bundle ts2js.ts > ts2js.ts.js
view raw run hosted with ❤ by GitHub



bundle前後


import * as path from "https://deno.land/std@0.97.0/path/mod.ts"
function 絶対Pathに変換(p: string): string{
return path.fromFileUrl(new URL(p, import.meta.url))
}
async function cmd(cmd:string): Promise<string>{
const p = Deno.run({cmd:['cmd', '/C', 'chcp 65001 & '+cmd], stdout:'piped'})
const o = await p.output()
const text = new TextDecoder().decode(o)
return text
}
const txt = await cmd('deno info')
const pathGen = txt.replace(/\\\\/g,'\\').match(/Emitted[^:]+:[^"]+"([^\n]+)"/)![1] + '\\'
console.log('Deno.args.length['+Deno.args.length+']')
for(let i=0, L=Deno.args.length; i<L ;i++){
const pathTS = 絶対Pathに変換(Deno.args[i])
const text = await cmd('deno cache '+pathTS)
console.log(text)
const pathUNC = pathTS.indexOf('\\\\')==0 ? 'UNC' : 'file'
const pathJS = pathGen + pathUNC + '\\' + pathTS.replace(/\\+/,'\\').replace(/:/,'') + '.js'
console.log('コピー元['+pathJS+']')
console.log('コピー先['+pathTS+'.js]')
await Deno.copyFile(pathJS, pathTS+'.js')
}
view raw ts2js.ts hosted with ❤ by GitHub
変換後は長過ぎるのでリンクで → after


bundleで作成されたjsがts同様に動作した





cacheファイルを使ってJavaScriptに変換するサンプルは、依存関係のファイルを含まないので、それはそれで何かの役に立つ場合もある…かもしれません。


0 件のコメント:

コメントを投稿