【问题标题】:How do I import functions from one CoffeeScript file to another?如何将函数从一个 CoffeeScript 文件导入到另一个文件?
【发布时间】:2021-06-21 04:18:45
【问题描述】:

我在 CoffeeScript 中有两个不同的文件,我想从另一个文件中的一个文件访问一个函数。我可以将一个文件中的函数导入另一个文件吗?

【问题讨论】:

    标签: function methods import coffeescript


    【解决方案1】:

    是的,它与 Javascript 中的相同。您可以使用 commonjs require 语法,或者如果您使用像 babel 这样的预处理器,您可以通过 import / export 语法使用模块

    需要

    您可以导出包含您喜欢的任何内容的对象,并在另一个文件中使用它。用一个例子最简单的解释:

    first.coffee

    a = (x) ->
      console.log "file first, function a, argument #{x}"
    
    b = 3.1415
    
    module.exports = 
      a: a
      b: b
    

    second.coffee:

    first = require './first'
    
    first.a 'test'
    console.log "b: #{first.b}"
    
    
      
    

    模块

    来自documentation

    CoffeeScript 支持 ES2015 模块,导入和导出语法非常相似:

    import './local-file.coffee'
    import 'coffeescript'
    
    import _ from 'underscore'
    import * as underscore from 'underscore'
    
    import { now } from 'underscore'
    import { now as currentTimestamp } from 'underscore'
    

    您需要使用 babel 进行转译,因为 Node / 浏览器默认不支持导入/导出。一个流行的例子是 webpack。这是official example

    你需要安装 @babel/core 和 @babel/preset-env 然后创建一个配置文件:

    npm install --save-dev @babel/core @babel/preset-env
    echo '{ "presets": ["@babel/env"] }' > .babelrc
    

    webpack.config.js

    module.exports = {
      module: {
        rules: [
          {
            test: /\.coffee$/,
            loader: 'coffee-loader',
            options: {
              transpile: {
                presets: ['@babel/env'],
              },
            },
          },
        ],
      },
    };
    

    【讨论】:

      猜你喜欢
      • 2018-05-02
      • 2019-09-25
      • 2020-08-18
      • 2017-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-22
      • 2021-09-09
      相关资源
      最近更新 更多