基于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

posted on 2022-05-28 17:03  荣锋亮  阅读(345)  评论(0编辑  收藏  举报

导航