buildtime vs runtime - 如何使用包代码本身共享Package.js中的变量/代码?

时间:2015-01-29 17:22:26

标签: meteor packages

我有一个包需要定义一堆资产文件(在构建时),包,测试以及包本身(在运行时)。

有没有办法分享这些变量?例如:

// package.js

// var shared across test and package def
var BrainFiles = [
    "data/begin.rive",
    "data/start.rive",
    "data/nav.rive"
  ]

Package.on_use(function(api) {
  api.addFiles(BrainFiles, ['server'], 
    {isAsset: true} 
  )

  ...
}

Package.on_test(function (api) {
  api.addFiles(BrainFiles, ['server'], 
    {isAsset: true} 
  )
  ...
}

// then within the package code i want to refer to Brainfiles

我想另一种方法是编写文件夹扫描功能,但该代码也必须在package.js和包代码之间共享。

1 个答案:

答案 0 :(得分:0)

它不漂亮,但我会创建一个Asset文件brain-files.json

//brain-files.json
[
  "data/begin.rive",
  "data/start.rive",
  "data/nav.rive"
]

使用fs

package.js中阅读/解析它
//package.js
Package.on_use(function(api) {
  var fs = Npm.require('fs')
  var BrainFiles = JSON.parse(fs.readFileSync('brain-files.json'));
  api.addFiles(BrainFiles, 'server', {isAsset: true});

  // sets a `BrainFiles` variable for other files that are included
  api.addFiles('brain-files.json', 'server', {isAsset: true});
  api.addFiles('read-brain-files.js', 'server');

  ...
}

使用Assets.getText()

在js文件read-brain-files.js中读取/解析
//read-brain-files.js
// no var, this should be accessible by all files in your package
BrainFiles = JSON.parse(Assets.getText('/packages/my-package/brain-files.json'));