简体   繁体   中英

Node.js Babel build and npm module-alias

I'm using module-alias for my Node.js + Express.js project, running it with Babel for ES2015 support.

App works perfect when started with babel-node , however, if I first build it with babel (from package.json ):

"build": "babel ./app --out-dir ./app_dist"

And then start:

"start": "node ./app_dist/bin/www"

It obviously cannot find the correct path specified with module-alias. Instead of looking into app_dist , Node.js searches for import in app , finds ES2015 import directive which it does not understand and throws:

SyntaxError: Unexpected token import

If I change aliases before start of that build, from app to app_dist , it works, but the question is, how to map those aliases (or how to use different _moduleAliases configuration) so that app resolves the paths correctly on development and production?

Maybe there is another way to alias modules with such stack? Thanks in advance.

Found solution for this issue.

In order to set the relative path aliases with module-alias , they shoul be defined not in package.json , but in JavaScript file inside the root directory that will be transpiled with Babel.

In my case, creating an aliases.js script inside config directory like this:

import path from 'path';
import moduleAlias from 'module-alias';

moduleAlias.addAlias('@root', path.resolve(__dirname, '../../'));

Will result in path resolving relatively to the current working directory, solving described problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM