Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export es6 class in Babel - Cannot find module

I have seen these two answers on SO:

Exporting a class with ES6 (Babel)

Trying to export a class as a module ES6 babel

I am not using Browserify, just Gulp and Node, just wanted to preface.


File/Folder Structure:

./

./gulpfile.js

./_GULP

./_GULP/main_config.es6

./_GULP/_classes/Gcfg.es6


Question Setup

I am exporting a class Gcfg.es6 file, like so:

export default class Gcfg {
   constructor() {
        this.rootDir = './';
        this.latestDir = './_LATEST/';
        this.srcFolder = './_SRC/';
        ...
   }

    getSrcDir(dir="") {
        return this.srcFolder + dir;
    }
    ...
}

In main_config.es6 I am trying to import:

import Gcfg from '_classes/Gcfg';

Following this GitHub post:

https://github.com/babel/babel/issues/849

I assumed I was doing it all correctly. I am using WebStorm and have a "File Watcher" setup to run Babel on save of a .es6 file. I am not doing anything fancy there, the only optional flags I am using are:

--source-maps and --out-file $FileNameWithoutExtension$.js $FilePath$

$FileNameWithoutExtension$.js is a WebStorm application variables and just is the file being loaded by the watcher and $FilePath$ is the absolute path to the file.

So the command looks like this (I believe I actually do not see it executed):

babel --source-maps --out-file main_config.js ./_GULP/ etc for the other files...

All files are processed fine by babel I believe. I see the exports and requires in the generated JS.

tl;dr

In gulpfile.js I am doing:

gCfg = require('./_GULP/main_config'); <- this require works!

However, when I try to run GULP it immediately fails and in the console I get:

Error: Cannot find module '_classes/Gcfg'
at Function.Module._resolveFilename (module.js:336:15)
at Function.Module._load (module.js:286:25)
at Module.require (module.js:365:17)
at require (module.js:384:17)
at Object.<anonymous> (/Users/xxx/xxx/xxx/xxx/xxx/_GULP/main_config.js:9:20)
at Module._compile (module.js:434:26)
at Object.Module._extensions..js (module.js:452:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Module.require (module.js:365:17)
at require (module.js:384:17)

The Question

Why am I unable to export the class in Gcfg.es6 and import it into main.es6 using es6 import/export? Is there a polyfill needed (I am loading bable/polyfill)? Is it that I have _'s in my path? I have just been thrashing on this for too long.

Thanks!

like image 671
Red2678 Avatar asked Oct 08 '15 03:10

Red2678


1 Answers

Well for one thing you have:

import Gcfg from '_classes/Gcfg';

If you're compiling to CommonJS and you don't have anything special setup, Node is going to try to load node_modules/_classes/Gcfg. You probably want:

import Gcfg from './_classes/Gcfg';
like image 128
JMM Avatar answered Oct 28 '22 19:10

JMM