[英]Treat self as a node module for npm
I have a javascript project which is released as a node module. 我有一个javascript项目,作为节点模块发布。 For some reasons, I have some source code using relative paths to import other files in this project:
出于某些原因,我有一些源代码使用相对路径来导入此项目中的其他文件:
// <this_module_path>/action/foo.js
import execution from './execution';
import types from '../types';
and also using a module name as a root path to import other files in this project: 并使用模块名称作为根路径来导入此项目中的其他文件:
// <this_module_path>/action/doSomething.js
// Using module name to import
// equals to import './helpers.js' in this case (in the same folder)
import executionHelpers from 'this-module/action/helpers.js';
// equals to import '../types/helpers' in this case
import typeHelpers from 'this-module/types/helpers.js';
How can I have a such file to import other project files using its module name rather than relative paths? 如何使用模块名称而不是相对路径导入其他项目文件?
NodeJS uses CommonJS to import javascript moduels. NodeJS使用CommonJS导入javascript模块。 There is no clear timeline for adding ES6
import / export
syntax to NodeJS. 向NodeJS添加ES6
import / export
语法没有明确的时间表。 So you need to transpile your code using Babel to CommonJS module system before you can run it on NodeJS. 因此,您需要使用Babel将代码转换为CommonJS模块系统,然后才能在NodeJS上运行它。
Create a separate package for your this-module
module. this-module
模块创建单独的包。 The package needs to be created inside node_modules
directory of your main module. 需要在主模块的
node_modules
目录中创建包。 You can do this using npm init
command inside the node_modules
directory. 您可以使用
node_modules
目录中的npm init
命令执行此操作。
Inside that file, you need to create a Javascript file (conventionally called index.js
and make it the main script of that package. 在该文件中,您需要创建一个Javascript文件(通常称为
index.js
并使其成为该包的主脚本)。
Your package.json
should look something like this: 你的
package.json
应该是这样的:
{
"name": "test",
"version": "1.0.0",
"description": "",
"main": "index.js",
}
index.js
you can export your variables (such as helpers
and types
) and you can easily import them in your main package. index.js
您可以导出变量(例如helpers
和types
),并且可以轻松地将它们导入主程序包中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.