如何使用节点模块打包资产 [英] How to package assets with a node module

查看:64
本文介绍了如何使用节点模块打包资产的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在节点模块(模块B)中包含一些模拟数据,然后能够从调用模块(模块A)中引用这些数据。数据是模块B的 / data 目录中的文本文件。我在模块B上有一个函数,该函数使用__dirname调用数据,但是当此函数为从模块A调用,__ dirname引用模块A的目录...而不是模块B。
包括这样的资产数据并将其在使用模块中可用的最佳方法是什么?

I'm trying to include some simulation data with a node module (module B) and then be able to reference that data from the calling module (module A). The data is a text file in the /data directory of module B. I have a function on module B that calls up the data using __dirname, but of course when this function is called from module A, the __dirname references the directory of module A... not module B. What's the best way to include asset data like this and make it available in the consuming module?

推荐答案

打包模块时,可以使用 package.json的个文件属性,将所有资产与您的模块捆绑在一起。

When packaging a module you can use the files property of package.json to bundle any assets along with your module.

然后,在该模块中,您可以使用 relative 路径引用您包含的资产。

Then, in that module, you can use a relative path to reference your included asset.

想象一个具有以下文件结构的模块:

Imagine a module with this file structure:

 -assets
   |-data.txt
 index.js

在您的 package.json 中,您可能有个文件部分如下:

In your package.json you might have a files section that looked like:

files: [
    'index.js',
    'assets/data.txt'
]

index.js 中,您可以像这样公开资产数据:

And in index.js you could expose your asset data like so:

let fs = import 'fs';

function getAssetData() {
   return fs.readFileSync('./assets/data.txt')
}

module.exports = { getAssetData };

这篇关于如何使用节点模块打包资产的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆