1

I have a javascript project which is released as a node module. 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?

Xaree Lee
  • 3,188
  • 3
  • 34
  • 55
  • 1
    Are you using Babel to transpile your code to convert `import` syntax to CommonJS? – bman Jan 09 '17 at 02:24

1 Answers1

0

NodeJS uses CommonJS to import javascript moduels. There is no clear timeline for adding ES6 import / export syntax to NodeJS. So you need to transpile your code using Babel to CommonJS module system before you can run it on NodeJS.

How to do this using CommonJS

  1. Create a separate package for your this-module module. The package needs to be created inside node_modules directory of your main module. You can do this using npm init command inside the node_modules directory.

  2. Inside that file, you need to create a Javascript file (conventionally called index.js and make it the main script of that package.

Your package.json should look something like this:

{
  "name": "test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
}
  1. In the index.js you can export your variables (such as helpers and types) and you can easily import them in your main package.
Community
  • 1
  • 1
bman
  • 5,016
  • 4
  • 36
  • 69