• 跳至… +
    browser.coffee cake.coffee coffeescript.coffee command.coffee grammar.coffee helpers.coffee index.coffee lexer.coffee nodes.coffee optparse.coffee register.coffee repl.coffee rewriter.coffee scope.litcoffee sourcemap.litcoffee
  • command.coffee

  • §

    coffee 實用程式。處理 CoffeeScript 的指令列編譯成各種形式:儲存到 .js 檔案或列印到 stdout 或每次儲存來源時重新編譯,列印為權杖串流或語法樹,或啟動互動式 REPL。

  • §

    外部相依性。

    fs             = require 'fs'
    path           = require 'path'
    helpers        = require './helpers'
    optparse       = require './optparse'
    CoffeeScript   = require './'
    {spawn, exec}  = require 'child_process'
    {EventEmitter} = require 'events'
    
    useWinPathSep  = path.sep is '\\'
  • §

    允許 CoffeeScript 發射 Node.js 事件。

    helpers.extend CoffeeScript, new EventEmitter
    
    printLine = (line) -> process.stdout.write line + '\n'
    printWarn = (line) -> process.stderr.write line + '\n'
    
    hidden = (file) -> /^\.|~$/.test file
  • §

    與 -h/--help 結合列印的說明橫幅。

    BANNER = '''
      Usage: coffee [options] path/to/script.coffee [args]
    
      If called without options, `coffee` will run your script.
    '''
  • §

    coffee 知道如何處理的所有有效選項旗標清單。

    SWITCHES = [
      [      '--ast',               'generate an abstract syntax tree of nodes']
      ['-b', '--bare',              'compile without a top-level function wrapper']
      ['-c', '--compile',           'compile to JavaScript and save as .js files']
      ['-e', '--eval',              'pass a string from the command line as input']
      ['-h', '--help',              'display this help message']
      ['-i', '--interactive',       'run an interactive CoffeeScript REPL']
      ['-j', '--join [FILE]',       'concatenate the source CoffeeScript before compiling']
      ['-l', '--literate',          'treat stdio as literate style coffeescript']
      ['-m', '--map',               'generate source map and save as .js.map files']
      ['-M', '--inline-map',        'generate source map and include it directly in output']
      ['-n', '--nodes',             'print out the parse tree that the parser produces']
      [      '--nodejs [ARGS]',     'pass options directly to the "node" binary']
      [      '--no-header',         'suppress the "Generated by" header']
      ['-o', '--output [PATH]',     'set the output path or path/filename for compiled JavaScript']
      ['-p', '--print',             'print out the compiled JavaScript']
      ['-r', '--require [MODULE*]', 'require the given module before eval or REPL']
      ['-s', '--stdio',             'listen for and compile scripts over stdio']
      ['-t', '--transpile',         'pipe generated JavaScript through Babel']
      [      '--tokens',            'print out the tokens that the lexer/rewriter produce']
      ['-v', '--version',           'display the version number']
      ['-w', '--watch',             'watch scripts for changes and rerun commands']
    ]
  • §

    所有函式共用的頂層物件。

    opts         = {}
    sources      = []
    sourceCode   = []
    notSources   = {}
    watchedDirs  = {}
    optionParser = null
    
    exports.buildCSOptionParser = buildCSOptionParser = ->
      new optparse.OptionParser SWITCHES, BANNER
  • §

    透過分析通過的選項並決定要採取的動作來執行 coffee。許多旗標會導致我們在編譯任何內容之前轉移。在 -- 之後通過的旗標將逐字傳遞給您的指令碼作為 process.argv 中的引數

    exports.run = ->
      optionParser = buildCSOptionParser()
      try parseOptions()
      catch err
        console.error "option parsing error: #{err.message}"
        process.exit 1
    
      if (not opts.doubleDashed) and (opts.arguments[1] is '--')
        printWarn '''
          coffee was invoked with '--' as the second positional argument, which is
          now deprecated. To pass '--' as an argument to a script to run, put an
          additional '--' before the path to your script.
    
          '--' will be removed from the argument list.
        '''
        printWarn "The positional arguments were: #{JSON.stringify opts.arguments}"
        opts.arguments = [opts.arguments[0]].concat opts.arguments[2..]
  • §

    讓 REPL CLI 使用全域環境,以便 (a) 與 node REPL CLI 保持一致,因此,(b) 使修改原生原型 (例如「色彩」和「糖」) 的套件按預期工作。

      replCliOpts = useGlobal: yes
      opts.prelude = makePrelude opts.require       if opts.require
      replCliOpts.prelude = opts.prelude
      replCliOpts.transpile = opts.transpile
      return forkNode()                             if opts.nodejs
      return usage()                                if opts.help
      return version()                              if opts.version
      return require('./repl').start(replCliOpts)   if opts.interactive
      return compileStdio()                         if opts.stdio
      return compileScript null, opts.arguments[0]  if opts.eval
      return require('./repl').start(replCliOpts)   unless opts.arguments.length
      literals = if opts.run then opts.arguments.splice 1 else []
      process.argv = process.argv[0..1].concat literals
      process.argv[0] = 'coffee'
    
      if opts.output
        outputBasename = path.basename opts.output
        if '.' in outputBasename and
           outputBasename not in ['.', '..'] and
           not helpers.ends(opts.output, path.sep)
  • §

    指定了輸出檔名,例如 /dist/scripts.js。

          opts.outputFilename = outputBasename
          opts.outputPath = path.resolve path.dirname opts.output
        else
  • §

    指定了輸出路徑,例如 /dist。

          opts.outputFilename = null
          opts.outputPath = path.resolve opts.output
    
      if opts.join
        opts.join = path.resolve opts.join
        console.error '''
    
        The --join option is deprecated and will be removed in a future version.
    
        If for some reason it's necessary to share local variables between files,
        replace...
    
            $ coffee --compile --join bundle.js -- a.coffee b.coffee c.coffee
    
        with...
    
            $ cat a.coffee b.coffee c.coffee | coffee --compile --stdio > bundle.js
    
        '''
      for source in opts.arguments
        source = path.resolve source
        compilePath source, yes, source
    
    makePrelude = (requires) ->
      requires.map (module) ->
        [full, name, module] = match if match = module.match(/^(.*)=(.*)$/)
        name or= helpers.baseFileName module, yes, useWinPathSep
        "global['#{name}'] = require('#{module}')"
      .join ';'
  • §

    編譯路徑,可以是指令碼或目錄。如果通過目錄,則遞迴編譯其中的所有「.coffee」、「.litcoffee」和「.coffee.md」擴充功能來源檔案和所有子目錄。

    compilePath = (source, topLevel, base) ->
      return if source in sources   or
                watchedDirs[source] or
                not topLevel and (notSources[source] or hidden source)
      try
        stats = fs.statSync source
      catch err
        if err.code is 'ENOENT'
          console.error "File not found: #{source}"
          process.exit 1
        throw err
      if stats.isDirectory()
        if path.basename(source) is 'node_modules'
          notSources[source] = yes
          return
        if opts.run
          compilePath findDirectoryIndex(source), topLevel, base
          return
        watchDir source, base if opts.watch
        try
          files = fs.readdirSync source
        catch err
          if err.code is 'ENOENT' then return else throw err
        for file in files
          compilePath (path.join source, file), no, base
      else if topLevel or helpers.isCoffee source
        sources.push source
        sourceCode.push null
        delete notSources[source]
        watch source, base if opts.watch
        try
          code = fs.readFileSync source
        catch err
          if err.code is 'ENOENT' then return else throw err
        compileScript source, code.toString(), base
      else
        notSources[source] = yes
    
    findDirectoryIndex = (source) ->
      for ext in CoffeeScript.FILE_EXTENSIONS
        index = path.join source, "index#{ext}"
        try
          return index if (fs.statSync index).isFile()
        catch err
          throw err unless err.code is 'ENOENT'
      console.error "Missing index.coffee or index.litcoffee in #{source}"
      process.exit 1
  • §

    根據請求的選項,編譯包含給定程式碼的單一來源指令碼。如果直接評估指令碼,請將 __filename、__dirname 和 module.filename 設定為相對於指令碼路徑正確的內容。

    compileScript = (file, input, base = null) ->
      options = compileOptions file, base
      try
        task = {file, input, options}
        CoffeeScript.emit 'compile', task
        if opts.tokens
          printTokens CoffeeScript.tokens task.input, task.options
        else if opts.nodes
          printLine CoffeeScript.nodes(task.input, task.options).toString().trim()
        else if opts.ast
          compiled = CoffeeScript.compile task.input, task.options
          printLine JSON.stringify(compiled, null, 2)
        else if opts.run
          CoffeeScript.register()
          CoffeeScript.eval opts.prelude, task.options if opts.prelude
          CoffeeScript.run task.input, task.options
        else if opts.join and task.file isnt opts.join
          task.input = helpers.invertLiterate task.input if helpers.isLiterate file
          sourceCode[sources.indexOf(task.file)] = task.input
          compileJoin()
        else
          compiled = CoffeeScript.compile task.input, task.options
          task.output = compiled
          if opts.map
            task.output = compiled.js
            task.sourceMap = compiled.v3SourceMap
    
          CoffeeScript.emit 'success', task
          if opts.print
            printLine task.output.trim()
          else if opts.compile or opts.map
            saveTo = if opts.outputFilename and sources.length is 1
              path.join opts.outputPath, opts.outputFilename
            else
              options.jsPath
            writeJs base, task.file, task.output, saveTo, task.sourceMap
      catch err
        CoffeeScript.emit 'failure', err, task
        return if CoffeeScript.listeners('failure').length
        message = err?.stack or "#{err}"
        if opts.watch
          printLine message + '\x07'
        else
          printWarn message
          process.exit 1
  • §

    附加適當的監聽器以編譯透過 stdin 進來的指令碼,並將它們寫回 stdout。

    compileStdio = ->
      if opts.map
        console.error '--stdio and --map cannot be used together'
        process.exit 1
      buffers = []
      stdin = process.openStdin()
      stdin.on 'data', (buffer) ->
        buffers.push buffer if buffer
      stdin.on 'end', ->
        compileScript null, Buffer.concat(buffers).toString()
  • §

    如果所有來源檔案都已讀取完畢,請將它們串接並編譯在一起。

    joinTimeout = null
    compileJoin = ->
      return unless opts.join
      unless sourceCode.some((code) -> code is null)
        clearTimeout joinTimeout
        joinTimeout = wait 100, ->
          compileScript opts.join, sourceCode.join('\n'), opts.join
  • §

    使用 fs.watch 監控來源 CoffeeScript 檔案,在檔案每次更新時重新編譯。可以與其他選項結合使用,例如 --print。

    watch = (source, base) ->
      watcher        = null
      prevStats      = null
      compileTimeout = null
    
      watchErr = (err) ->
        throw err unless err.code is 'ENOENT'
        return unless source in sources
        try
          rewatch()
          compile()
        catch
          removeSource source, base
          compileJoin()
    
      compile = ->
        clearTimeout compileTimeout
        compileTimeout = wait 25, ->
          fs.stat source, (err, stats) ->
            return watchErr err if err
            return rewatch() if prevStats and
                                stats.size is prevStats.size and
                                stats.mtime.getTime() is prevStats.mtime.getTime()
            prevStats = stats
            fs.readFile source, (err, code) ->
              return watchErr err if err
              compileScript(source, code.toString(), base)
              rewatch()
    
      startWatcher = ->
        watcher = fs.watch source
        .on 'change', compile
        .on 'error', (err) ->
          throw err unless err.code is 'EPERM'
          removeSource source, base
    
      rewatch = ->
        watcher?.close()
        startWatcher()
    
      try
        startWatcher()
      catch err
        watchErr err
  • §

    監控目錄中的檔案是否有新增內容。

    watchDir = (source, base) ->
      watcher        = null
      readdirTimeout = null
    
      startWatcher = ->
        watcher = fs.watch source
        .on 'error', (err) ->
          throw err unless err.code is 'EPERM'
          stopWatcher()
        .on 'change', ->
          clearTimeout readdirTimeout
          readdirTimeout = wait 25, ->
            try
              files = fs.readdirSync source
            catch err
              throw err unless err.code is 'ENOENT'
              return stopWatcher()
            for file in files
              compilePath (path.join source, file), no, base
    
      stopWatcher = ->
        watcher.close()
        removeSourceDir source, base
    
      watchedDirs[source] = yes
      try
        startWatcher()
      catch err
        throw err unless err.code is 'ENOENT'
    
    removeSourceDir = (source, base) ->
      delete watchedDirs[source]
      sourcesChanged = no
      for file in sources when source is path.dirname file
        removeSource file, base
        sourcesChanged = yes
      compileJoin() if sourcesChanged
  • §

    從我們的來源清單和來源程式碼快取中移除檔案。也可以選擇移除已編譯的 JS 版本。

    removeSource = (source, base) ->
      index = sources.indexOf source
      sources.splice index, 1
      sourceCode.splice index, 1
      unless opts.join
        silentUnlink outputPath source, base
        silentUnlink outputPath source, base, '.js.map'
        timeLog "removed #{source}"
    
    silentUnlink = (path) ->
      try
        fs.unlinkSync path
      catch err
        throw err unless err.code in ['ENOENT', 'EPERM']
  • §

    取得來源檔案對應的輸出 JavaScript 路徑。

    outputPath = (source, base, extension=".js") ->
      basename  = helpers.baseFileName source, yes, useWinPathSep
      srcDir    = path.dirname source
      dir = unless opts.outputPath
        srcDir
      else if source is base
        opts.outputPath
      else
        path.join opts.outputPath, path.relative base, srcDir
      path.join dir, basename + extension
  • §

    遞迴 mkdir,例如 mkdir -p。

    mkdirp = (dir, fn) ->
      mode = 0o777 & ~process.umask()
    
      do mkdirs = (p = dir, fn) ->
        fs.exists p, (exists) ->
          if exists
            fn()
          else
            mkdirs path.dirname(p), ->
              fs.mkdir p, mode, (err) ->
                return fn err if err
                fn()
  • §

    使用已編譯的程式碼寫出 JavaScript 來源檔案。預設情況下,檔案會以 .js 檔案寫入 cwd,且名稱相同,但輸出目錄可以使用 --output 自訂。

    如果提供了 generatedSourceMap,這會將 .js.map 檔案寫入與 .js 檔案相同的目錄中。

    writeJs = (base, sourcePath, js, jsPath, generatedSourceMap = null) ->
      sourceMapPath = "#{jsPath}.map"
      jsDir  = path.dirname jsPath
      compile = ->
        if opts.compile
          js = ' ' if js.length <= 0
          if generatedSourceMap then js = "#{js}\n//# sourceMappingURL=#{helpers.baseFileName sourceMapPath, no, useWinPathSep}\n"
          fs.writeFile jsPath, js, (err) ->
            if err
              printLine err.message
              process.exit 1
            else if opts.compile and opts.watch
              timeLog "compiled #{sourcePath}"
        if generatedSourceMap
          fs.writeFile sourceMapPath, generatedSourceMap, (err) ->
            if err
              printLine "Could not write source map: #{err.message}"
              process.exit 1
      fs.exists jsDir, (itExists) ->
        if itExists then compile() else mkdirp jsDir, compile
  • §

    方便更簡潔的 setTimeouts。

    wait = (milliseconds, func) -> setTimeout func, milliseconds
  • §

    在監控指令碼時,使用時間戳記記錄變更會很有用。

    timeLog = (message) ->
      console.log "#{(new Date).toLocaleTimeString()} - #{message}"
  • §

    漂亮列印一串沒有位置資料的符號。

    printTokens = (tokens) ->
      strings = for token in tokens
        tag = token[0]
        value = token[1].toString().replace(/\n/, '\\n')
        "[#{tag} #{value}]"
      printLine strings.join(' ')
  • §

    使用 OptionParser 模組 從 process.argv 中萃取所有在 SWITCHES 中指定的選項。

    parseOptions = ->
      o = opts      = optionParser.parse process.argv[2..]
      o.compile     or=  !!o.output
      o.run         = not (o.compile or o.print or o.map)
      o.print       = !!  (o.print or (o.eval or o.stdio and o.compile))
  • §

    傳遞給 CoffeeScript 編譯器的編譯時間選項。

    compileOptions = (filename, base) ->
      if opts.transpile
  • §

    使用者已要求 CoffeeScript 編譯器也透過 Babel 轉譯。我們不將 Babel 納入相依性,因為我們希望盡量避免相依性,而且大多數使用者可能不會依賴我們為他們轉譯;我們假設大多數使用者可能會在沒有轉譯的情況下執行 CoffeeScript 的輸出(現代 Node 或常青瀏覽器),或使用適當的建置鏈,例如 Gulp 或 Webpack。

        try
          require '@babel/core'
        catch
          try
            require 'babel-core'
          catch
  • §

    根據 coffee 是在本地或全域執行,提供適當的說明。

            if require.resolve('.').indexOf(process.cwd()) is 0
              console.error '''
                To use --transpile, you must have @babel/core installed:
                  npm install --save-dev @babel/core
                And you must save options to configure Babel in one of the places it looks to find its options.
                See https://coffeescript.lang.tw/#transpilation
              '''
            else
              console.error '''
                To use --transpile with globally-installed CoffeeScript, you must have @babel/core installed globally:
                  npm install --global @babel/core
                And you must save options to configure Babel in one of the places it looks to find its options, relative to the file being compiled or to the current folder.
                See https://coffeescript.lang.tw/#transpilation
              '''
            process.exit 1
    
        opts.transpile = {} unless typeof opts.transpile is 'object'
  • §

    將 Babel 的參考傳遞給編譯器,以便 CLI 可以使用轉譯選項。我們需要這樣做,以便 Webpack 等工具可以 require('coffeescript') 並正確建置,而不會嘗試需要 Babel。

        opts.transpile.transpile = CoffeeScript.transpile
  • §

    Babel 會根據其 filename 選項中傳遞給它的路徑,搜尋其選項(.babelrc 檔案、.babelrc.js 檔案、具有 babel 鍵的 package.json 檔案等)。請確定我們有路徑可以傳遞。

        unless opts.transpile.filename
          opts.transpile.filename = filename or path.resolve(base or process.cwd(), '<anonymous>')
      else
        opts.transpile = no
    
      answer =
        filename: filename
        literate: opts.literate or helpers.isLiterate(filename)
        bare: opts.bare
        header: opts.compile and not opts['no-header']
        transpile: opts.transpile
        sourceMap: opts.map
        inlineMap: opts['inline-map']
        ast: opts.ast
    
      if filename
        if base
          cwd = process.cwd()
          jsPath = outputPath filename, base
          jsDir = path.dirname jsPath
          answer = helpers.merge answer, {
            jsPath
            sourceRoot: path.relative(jsDir, cwd) + path.sep
            sourceFiles: [path.relative cwd, filename]
            generatedFile: helpers.baseFileName(jsPath, no, useWinPathSep)
          }
        else
          answer = helpers.merge answer,
            sourceRoot: ""
            sourceFiles: [helpers.baseFileName filename, no, useWinPathSep]
            generatedFile: helpers.baseFileName(filename, yes, useWinPathSep) + ".js"
      answer
  • §

    使用傳遞給 node 二進位檔的 --nodejs 中的引數,啟動新的 Node.js 實例,並保留其他選項。

    forkNode = ->
      nodeArgs = opts.nodejs.split /\s+/
      args     = process.argv[1..]
      args.splice args.indexOf('--nodejs'), 2
      p = spawn process.execPath, nodeArgs.concat(args),
        cwd:        process.cwd()
        env:        process.env
        stdio:      [0, 1, 2]
      for signal in ['SIGINT', 'SIGTERM']
        process.on signal, do (signal) ->
          -> p.kill signal
      p.on 'exit', (code) -> process.exit code
  • §

    列印 --help 使用訊息並結束。不會顯示已棄用的開關。

    usage = ->
      printLine optionParser.help()
  • §

    列印 --version 訊息並結束。

    version = ->
      printLine "CoffeeScript version #{CoffeeScript.VERSION}"