Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Provide API method to transform a source code string #20

Open
mtsknn opened this issue Jun 24, 2021 · 3 comments
Open

Provide API method to transform a source code string #20

mtsknn opened this issue Jun 24, 2021 · 3 comments

Comments

@mtsknn
Copy link

mtsknn commented Jun 24, 2021

The currently provided transform method takes a path to a file (or an array of paths) and optionally writes the transformed file(s) to the file system.

It would be nice to provide another method which takes a source code string and returns a transformed source code string. For example:

import {transform} from 'cjstoesm'

const input = `
  const {foo: bar} = require("./my-module")
  module.exports = {baz: 3}
`

await transform({ input })
//=> 'import {foo as bar} from "./my-module.js"\nexport const baz = 3'

(The method name could be different.)

@caoxiemeihao
Copy link

It's very useful! 👏👏👏👏

@caoxiemeihao
Copy link

Maybe you can use it like this

import { transpileModule, ModuleKind } from 'typescript'
import { cjsToEsm } from 'cjstoesm'

const input = `
  const {foo: bar} = require("./my-module")
  module.exports = {baz: 3}
`

const result = transpileModule(input, {
  transformers: cjsToEsm(),
  compilerOptions: {
    module: ModuleKind.ES2020,
  },
})

// console.log(result.outputText)

@ghh-l-djl
Copy link

I have the same needs

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants