简体   繁体   中英

Detect inside a Gatsby plugin if the current project is using typescript?

Is it possible? Maybe using something like https://www.gatsbyjs.org/docs/node-apis/#resolvableExtensions ?

thanks in advance

Hhhm perhaps you can hook into onCreateWebpackConfig & check the extensions there:

// gatsby-node.js

exports.onCreateWebpackConfig = ({ getConfig }) => {
  const { extensions } = getConfig().resolve
  const hasTs = extensions.find(ext => ['.ts', '.tsx'].includes(ext))
  console.log(hasTs) // undefined if no ts
}

But if you need that information upfront, the most sure shot is to check if there are any ts files in src directory with something like glob

const path = require(`path`)
const glob = require(`glob`)

const checkTs = ({ directory }) => {
  const srcFolder = path.join(directory, 'src')
  const tsFiles = glob.sync(`${srcFolder}/**/*.ts{,x}`)
  return (tsFiles.length > 0)
}

exports.onPreInit = ({ store }) => {
  const { directory } = store.getState().program
  const hasTs = checkTs({ directory })
  console.log({ hasTs })
}

I'm curious why you'd need this information though? If I were implementing a typescript-specific feature, I'd trust user to only use it if they use typescript.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM