如何在节点中需要一个非npm主文件的文件?
的package.json:
... "name": "mypackage", "main": "src/index.js" ...
目录结构:
|- src/ |--- index.js |--- other.js
我可以要求src/index.js
与require('mypackage');
,但我怎么能要求src/other.js
?
如果答案是require('mypackage/src/other');
,有没有办法让它,所以我可以要求与require('mypackage/other');
(即教学节点什么源文件目录是你的模块?
AFAIK你必须明确地暴露在根:
目录结构:
|- src/ |--- index.js |--- other.js |- other.js
然后在/other.js
module.exports = require('src/other.js');
现在你可以做require('mypackage/other')
我目前正在研究完全相同的事情。
Package.json
有一个名为'files'的属性:
http://blog.kewah.com/2014/npm-as-a-front-end-package-manager/
https://docs.npmjs.com/files/package.json
“文件”字段是要包含在项目中的文件数组。 如果您在数组中命名一个文件夹,那么它也将包含该文件夹内的文件。
但我还没有find如何做一个这样的文件的导入/要求。 我真的不明白在列出这些文件的另一点,然后能够import/require
他们?
我能够从包中导入文件,如果它列在这个文件数组中。
{ "name": "local-ui-utilities", "version": "0.0.1", "description": "LOCAL UI Utilities", "main": "index.jsx", "author": "Norbert de Langen", "license": "none", "dependencies": { }, "files": [ "/colors/sets/variables.css" ] }
我能够使用postcss-import从包中导入css文件:
@import "local-ui-utilities/colors/sets/a.css";
这可能不是你的用例,但是postcss-import只是使用npm。 所以这应该也适用于你的用例,我想。
这个问题和接受的答案似乎相关: 节点/ NPM:一个NPM包可以暴露多个文件吗?
您必须明确地公开根文件夹中的文件,但是许多项目(包括lodash的旧版本)都会将其作为预发布步骤的一部分。 实际上,有一个软件包完全符合@Creynders的build议,在根文件夹中添加module.exports = require('./path/to/file')
文件。 有一段时间,我写了一篇关于入门的指导 ,但其要点非常简单。
安装
npm install --save-dev generate-export-aliases
configuration
{ "name": "my-package", "scripts": { "prepublish": "generate-export-aliases" }, "config": { "exportAliases": { "other": "./src/other" } } }
使用
const other = require('my-package/other')
免责声明:我是包裹的作者