sophgdn
sophgdn

Reputation: 17

How do I import functions from one CoffeeScript file to another?

I have two different files both in CoffeeScript and I'd like to access a function from one file in the other. Am I able to import a function from one file into another file?

Upvotes: 1

Views: 1782

Answers (1)

caffeinated.tech
caffeinated.tech

Reputation: 6548

Yes, it's the same as in Javascript. You can use the commonjs require syntax, or if you use a preprocessor like babel you can use modules via the import / export syntax

Require

You can export an object containing whatever you like, and use it in another file. Easiest explained with an example:

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}"


  

Modules

From the documentation

ES2015 modules are supported in CoffeeScript, with very similar import and export syntax:

import './local-file.coffee'
import 'coffeescript'

import _ from 'underscore'
import * as underscore from 'underscore'

import { now } from 'underscore'
import { now as currentTimestamp } from 'underscore'

You will need to transpile with babel, as import/export isn't supported by default in Node / browsers. A popular example is webpack. Here is an official example

You'll need to install @babel/core and @babel/preset-env and then create a configuration file:

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'],
          },
        },
      },
    ],
  },
};

Upvotes: 1

Related Questions