【发布时间】:2021-06-21 04:18:45
【问题描述】:
我在 CoffeeScript 中有两个不同的文件,我想从另一个文件中的一个文件访问一个函数。我可以将一个文件中的函数导入另一个文件吗?
【问题讨论】:
标签: function methods import coffeescript
我在 CoffeeScript 中有两个不同的文件,我想从另一个文件中的一个文件访问一个函数。我可以将一个文件中的函数导入另一个文件吗?
【问题讨论】:
标签: function methods import coffeescript
是的,它与 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}"
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"] }' > .babelrcwebpack.config.js
module.exports = { module: { rules: [ { test: /\.coffee$/, loader: 'coffee-loader', options: { transpile: { presets: ['@babel/env'], }, }, }, ], }, };
【讨论】: