Yerko Palma
Yerko Palma

Reputation: 12329

How to load npm packages with ClosureCompiler.js

I want to try Google Closure Compiler, so I'm using it with the npm distribution closurecompiler.js. I'm using the closure compiler to traspile my es6 code to es5. It's not an option to change to babel transpiler.

So I started with some basic examples, and those worked fine, but I'm stuck importing some npm packages. This are my dependencies, from my package.json file

"dependencies": {
    "body-parser": "~1.5.2",
    "express": "~4.7.2",
    "method-override": "~2.1.2",
    "mongoose": "~3.6.2",
    "morgan": "~1.2.2",
    "vue": "^1.0.16",
    "vue-resource": "^0.7.0"
  }

Running the require command it is all working but if I run

import express from 'express'

I got the error

server.js:4: ERROR - Failed to load module "express"
  import express  from 'express'
  ^

the command used to make the transpile was

ccjs config/*.js server.js --externs=node > dist/server.js && node dist/server.js

I've tried it with and without the --externs=node option, but nothing changes. Note that sentences like

import database from './config/database'

works fine, the problem is only for the node_modules packages. So, how can I make those import work with closure compiler??

Upvotes: 2

Views: 1511

Answers (2)

Hermann
Hermann

Reputation: 1150

The trick was to pass the referenced files and package.json to the closure compiler using --js argument. Something like this:

java\
 -jar node_modules/google-closure-compiler/compiler.jar\
 --compilation_level=ADVANCED\
 --process_common_js_modules\
 --dependency_mode=STRICT\
 --js_output_file='./dist/compiled.js'\
 --module_resolution=NODE\
 --entry_point=./src/module\
 --js='./src/**.js'\
 --js='./node_modules/isarray/**.js'\
 --js='./node_modules/isarray/**package.json'

Check here.

However with express it is tricky, as it brings bunch of dependencies and compiler reports tons of errors on them.

Upvotes: 1

Tyler
Tyler

Reputation: 22116

The --js_module_root flag tells the compiler where modules are found. By default it looks only in the current directory, so you probably need to pass the node_modules directory as well, to make this work.

I haven't used the compiler with node myself but I think that should be all you need. If that works, please update the documentation at https://github.com/google/closure-compiler/wiki/JS-Modules or comment here to remind us to do that.

Upvotes: 2

Related Questions