1. 程式人生 > 其它 >基於typescript 開發njs 模組的一個玩法

基於typescript 開發njs 模組的一個玩法

如果體驗了njs 模組的能力會發現njs 是一個很不錯的js 模組,但是問題也不少,js 型別以及函式支援,同時npm模組支援也是
一個很大的問題,個人比較推薦的整合模式是基於rollup 構建

參考玩法

整合說明

因為缺少js 特性支援,我們可以基於core-js 進行擴充套件,對於npm 的整合我們可以使用rollup解決,njs-typescript-starter 是一個不錯的模版,剋有很好的整合使用
rollup 參考配置

 
// @ts-check
import addGitMsg from 'rollup-plugin-add-git-msg'
import babel from '@rollup/plugin-babel'
import commonjs from '@rollup/plugin-commonjs'
import resolve from '@rollup/plugin-node-resolve'
 
import pkg from './package.json'
   
// List of njs built-in modules.
const njsExternals = ['crypto', 'fs', 'querystring']
const isEnvProd = process.env.NODE_ENV === 'production'
 
/**
 * Plugin to fix syntax of the default export to be compatible with njs.
 * (https://github.com/rollup/rollup/pull/4182#issuecomment-1002241017)
 *
 * @return {import('rollup').OutputPlugin}
 */
const fixExportDefault = () => ({
  name: 'fix-export-default',
  renderChunk: (code) => ({
    code: code.replace(/\bexport { (\S+) as default };/, 'export default $1;'),
    map: null,
  }),
})
 
/**
 * @type {import('rollup').RollupOptions}
 */
const options = {
  input: 'src/mytest.ts',
  external: njsExternals,
  plugins: [
    // Transpile TypeScript sources to JS.
    babel({
      babelHelpers: 'bundled',
      envName: 'njs',
      extensions: ['.ts', '.mjs', '.js'],
    }),
    // Resolve node modules.
    resolve({
      extensions: ['.mjs', '.js', '.json', '.ts'],
    }),
    // Convert CommonJS modules to ES6 modules.
    commonjs(),
    // Fix syntax of the default export.
    fixExportDefault(),
    // Plugins to use in production mode only.
    ...isEnvProd ? [
      // Add git tag, commit SHA, build date and copyright at top of the file.
      addGitMsg(),
    ] : [],
  ],
  output: {
    file: pkg.main,
    format: 'es',
  },
}
export default options

說明

以上整合方案並不能徹底解決js 相容問題,而且通過測試發現問題還是不少的,實際上對於簡單模式使用njs 還不錯,如果是比較複雜的,目前還說還是推薦
基於openresty+TypeScriptToLua 是很不錯的選擇,可以很好的利用lua 方便的生態

參考資料

https://github.com/jirutka/babel-preset-njs
https://github.com/jirutka/njs-typescript-starter
https://github.com/jirutka/nginx-testing