Giter Club home page Giter Club logo

babel-plugin-module-resolver's People

Contributors

aesopwolf avatar amosyuen avatar anchengjian avatar andarist avatar artola avatar danez avatar datenreisender avatar dependabot[bot] avatar eldyvoon avatar fatfisz avatar greenkeeper[bot] avatar greenkeeperio-bot avatar hanachin avatar kelset avatar lolcube avatar markholland avatar matthieulemoine avatar mrydengren avatar nodkz avatar raulmatei avatar renatobenks avatar rohmanhm avatar rstoenescu avatar rvasseur31 avatar sassanh avatar simonsmith avatar telokis avatar tleunen avatar tptee avatar ypcrumble avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

babel-plugin-module-resolver's Issues

Alias on partial string?

I have a set of react components all in the same folder (a_la_lerna).

These components will be published to npm under a namespace, all prefixed by the react- string, I would like to make them depend by each other, example:

Structure:

/packages/foo/index.jsx // on npm will be @namespace/react-foo
/packages/bar/index.jsx // on npm will be @namespace/react-bar

foo/index.jsx:

import Bar from '@namespace/react-bar';
[...]

I would like to make webpack load the modules locally instead of npm while I'm developing, in practice, the import should be transpiled to:

import Bar from 'packages/bar';

Is it possible?

Force node_module dependencies to use module-resolver

Hi there,

Trying to hook this up with preact-compat to allow server rendering of preact using react-router.
The client side I use webpack to supply the alias, but I'd like to avoid webpacking the server-side code.

https://github.com/alexFaunt/preact-compat-dependecies

This is a repo with everything else taken out. If you npm run start it tries to load { Link } from react-router, which has a dependency on react - which I thought should be aliased to preact-compat using this module. Instead it throws Error: Cannot find module 'react'

I found on the babel register docs that I could supply require('babel-register')({ ignore: false }) but that results in a different error:

TypeError: Plugin 0 specified in "...preact-compat-dependencies/.babelrc" was expected to return a function but returned "undefined"

Any pointers would be great - I'm guessing it's just my config is missing something to make it use this resolver on the node_modules, but i can't see it.

Cheers

Unable to resolve module ../../../../src/StyleSheet

Hi

I've been trying to use your plugin module resolver with this config in my .babelrc:

{
  "presets": ["react-native"],
  "plugins": [
    [
      "module-resolver", {
        "root": ["./src"]
      },
    ]
  ],
}

And I'm having this error: Unable to resolve module ../../../../src/StyleSheet from '~/MyProject/node_modules/react-native/Libraries/react-native/react-native.js. Directory '~/MyProject/src/StyleSheet' doesn't exist.

The thing is this directory ~/MyProject/src/StyleSheet doesn't exist. I have file called styleSheet.js right here. Also, I don't get why the plugin would cause this issue, because I do not have this issue when the plugin is uninstalled ...

Any of you guys had something similar before ?

Thanks in advance :)

Is there support for using with `System.import()` (or alternative?)

I am using System.import() in my React project for lazy loading components and data to reduce initial bundle size.

["module-resolver", {"alias": { "data": "./src/data/"}}]

Sample code

System.import('data/faqs')
  .then(response => response.default)
  .then(faqs => this.setState({faqs}))

Error

ERROR in ./src/scripts/app/pages/FAQ.js
Module not found: Error: Can't resolve 'data/faqs' in '<truncated-path>/src/scripts/app/pages'
 @ ./src/scripts/app/pages/FAQ.js 42:6-39
 @ ./src/scripts/bundles/app.js
 @ multi app

Regular imports (import faqs from 'data/faqs') are working as expected, but not when using System.import()

If System.import() is not supported is there an alternative I can use?
For now I am just creating aliases within webpack config for the affected imports like below

resolve: {
  alias: {
    data: path.join(__dirname, 'src/data/')
  }
}

Would be nice if babel could handle all the aliases if possible :)

handle resolving duplicated files

I have these two files

app/component/home/Trader.js

app/component/contact/Trader.js

Now I import that second Trader in this component
app/component/sent/Sent.js

import Trader from 'Trader'
export default class Sent extends React.Component{
  render(){ 
    return <div>hello <Trader /></div>
  }
}

Problem: I will have the first trader file instead second one.

I understand that babel will resolve as soon as it find a match. However, I think we can do a warning. If babel found case like this. Give a warning, then users will know they have to change the file name in the import. They can change to something like below

import Trader from 'contact/Trader'
export default class Sent extends React.Component{
  render(){ 
    return <div>hello <Trader /></div>
  }
}

Usage with NodeJS api

I want to use this plugin when using the global Babel registrar - the one that patches require.

Can I just use a .babelrc or can i also just drop this plugin into my babel call?

nested dependencies

I tried out the root option, and it appeared to be working. however, I believe it's not re-writing the requires for a dependency inside another dependency potentially?

Warning: Module of equal name

Hi. Great plugin, thanks. However I'm getting a large number of warnings from Webpack when I run it through a build in the form of:

WARNING in ../~/react/react.js
There is another module with an equal name when case is ignored.
This can lead to unexpected behavior when compiling on a filesystem with other case-semantic.
Rename module if multiple modules are expected or use equal casing if one module is expected.

Just wondering if you'd come across it at any point? If there are no matches to your plugin, I do not get any warnings.

React Native platform extensions

This module does not seem to work with React Native Platform extensions import foo from 'components/foo'

where foo is one of foo.android.js or foo.ios.js

Works fine if i drop the android/ios part of the extension or if I fully specify ./components/foo

babelrc:

{
  'presets': ['react-native'],
  'plugins': ['transform-decorators-legacy',
  ["module-resolver", {
    "root": ["./app"],
    "alias": {
      "test": "./test",
      "underscore": "lodash"
    },
   "extensions": [".android.js", ".ios.js"]
  }]
  ]
}

Special chars aren't allowed in aliases

So, I'm fighting with this plugin...

I just want to define this:

  "babel": {
    "presets": [
      "react-app"
    ],
    "plugins": [
      [
        "module-resolver",
        {
          "root": [
            "./src"
          ],
          "alias": {
            "@src": "./src"
          }
        }
      ]
    ]
  },

So that I can import foo from '@src/foo' and it will point to my src/foo.js.

It doesn't work, when I run the tests, I get an error:

Cannot find module '../../foo' from 'sample.js

If I replace @src (on both the config and the import) with foobar, it works like a charm.

Aren't special characters supported in aliases?

Root path not working on Windows

Hello,

I can't figure out why, but following .babelrc config works fine for me on Linux.
In the opposite my colleagues have problems running this on Windows, they still need relative paths.

{
  "presets": ["react-native"],
  "plugins": [
    ["module-resolver", {
      "root": ["./src"],
      "alias": {
        "test": "./test"
      }
    }]
  ]
}

Any ideas?

Error - ... provided an invalid property of "default" - with 1.0.0 and babel 6

Uncaught Exception:
Error: Plugin 0 specified in "/home/mike/slack-wrapped-2/.babelrc" provided an invalid property of "default"
    at Plugin.init (/home/mike/slack-wrapped-2/node_modules/babel-core/lib/transformation/plugin.js:124:13)
    at Function.normalisePlugin (/home/mike/slack-wrapped-2/node_modules/babel-core/lib/transformation/file/options/option-manager.js:155:12)
    at /home/mike/slack-wrapped-2/node_modules/babel-core/lib/transformation/file/options/option-manager.js:183:30
    at Array.map (native)
    ...
{
  ...
  "plugins": [
    ["babel-plugin-module-alias", [
      { "src": "./src/main", "expose": "main" },
      { "src": "./src/web", "expose": "web" }
    ]]
  ]
}

I wonder if this is this related to babel/babel#2697?

Alias resolves to wrong alias when used inside aliased code

The behavior I have observed is that when I use an alias inside of another alias one path backward is somehow skimmed in my folder structure.

The same works with webpack which I use on the client side.

Babelrc:

{
  "presets": ["es2015", "stage-0"],

  "plugins": [
    ["module-resolver",
      {
        "root": [
          "./src"
        ],
        "alias": {
          "mythil": "./build/lib/mythil.js/src",
          "libbehoerdenglueck": "./build/lib/libbehoerdenglueck/src"
        }
      }]
  ]
}

Folder structure:

lib
├── libbehoerdenglueck
│   ├── data
│   │   └── ...
│   └── src
│       ├── constants.js
│       ├── hamburg.js
│       └── visit.js
└── mythil.js
    ├── COMMANDS.md
    └── src
        ├── array.js
        ├── dom.js
        ├── md5obj.js
        ├── number.js
        ├── object.js
        ├── string.js
        ├── time.js
        ├── util.js
        └── validation.js

Files are compiled into the build directory using this command:
./node_modules/.bin/babel src -d build && ./node_modules/.bin/babel lib -d build/lib && node build/index.js

The build dir then looks like this:

build
├── NetAppointmentApi.js
├── dump-pouch.js
├── dump.js
├── index.js
├── lib
│   ├── libbehoerdenglueck
│   │   └── src
│   │       ├── constants.js
│   │       ├── hamburg.js
│   │       └── visit.js
│   └── mythil.js
│       └── src
│           ├── array.js
│           ├── dom.js
│           ├── md5obj.js
│           ├── number.js
│           ├── object.js
│           ├── string.js
│           ├── time.js
│           ├── util.js
│           └── validation.js

When running the command compiling with babel works fine. However running the code encounters a module resolve error:

Error: Cannot find module '../../../build/lib/mythil.js/src/time'
    at Function.Module._resolveFilename (module.js:438:15)
    at Function.Module._load (module.js:386:25)
    at Module.require (module.js:466:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/Users/tobiasanhalt/Development/behoerdenglueck/build/lib/libbehoerdenglueck/src/constants.js:20:13)
    at Module._compile (module.js:541:32)
    at Object.Module._extensions..js (module.js:550:10)
    at Module.load (module.js:456:32)
    at tryModuleLoad (module.js:415:12)
    at Function.Module._load (module.js:407:3)
    at Module.require (module.js:466:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/Users/tobiasanhalt/Development/behoerdenglueck/build/lib/libbehoerdenglueck/src/visit.js:78:18)
    at Module._compile (module.js:541:32)
    at Object.Module._extensions..js (module.js:550:10)
    at Module.load (module.js:456:32)

In constants.js which is accessed through the alias libbehoerdenglueck the following line fails:
import { mToMs, sToMs, dToMs, hToMs } from 'mythil/time';

babel-plugin-module-resolver translates the alias mythil/time to ../../../build/lib/mythil.js/src/timeinstead of the correct ../../../../build/lib/mythil.js/src/time (one path backward is missing).

All that is pretty sad :(
Would love to see replications of the issue and possible workarounds.

Workaround:
find ./build -type f -name '*.js' -exec sed -i '' s@../../../build@../../../../build@ {} +

Best regards
Mythli

Missing index.js support

If you have 'components/index.js' file and want to use import module from 'components' plugin will require to write import module from 'components/index'

Can't get it to work in React Native

Works

import { FullScreen } from '../../styles/CommonStyles';

Unable to resolve module 'styles/CommonStyles [...]. Module does not exist in the module map or in these directories: [projectdir]/node_modules/styles

import { FullScreen } from 'styles/CommonStyles';

BTW, there is no node_module calles 'styles'

.babelrc

{
  "sourceMaps": true,
  "presets": [
      "react-native"
  ],
  "plugins": [
    ["module-resolver", {
        "root": ["./src"]
    }]
  ]
}

An in-range update of babel-plugin-transform-object-rest-spread is breaking the build 🚨

Version 6.20.0 of babel-plugin-transform-object-rest-spread just got published.

Branch Build failing 🚨
Dependency babel-plugin-transform-object-rest-spread
Current Version 6.19.0
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

As babel-plugin-transform-object-rest-spread is “only” a devDependency of this project it might not break production or downstream projects, but “only” your build or test tools – preventing new deploys or publishes.

I recommend you give this issue a high priority. I’m sure you can resolve this 💪


Status Details
  • continuous-integration/appveyor/branch AppVeyor build succeeded Details

  • ci/circleci Your tests failed on CircleCI Details

Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

findPluginOptions is undefined

I kept getting findPluginOptions is undefined on this line when using this plugin.
https://github.com/tleunen/babel-plugin-module-resolver/blob/master/src/index.js#L123

I needed to hack around it like this. (obviously not the correct solution but it works great with the hack applied)

        manipulateOptions: function manipulateOptions(babelOptions) {
            var findPluginOptions = babelOptions.plugins[0][0];
            if (findPluginOptions.root) {
                findPluginOptions.root = findPluginOptions.root.reduce(function (resolvedDirs, dirPath) {
                    if (_glob2.default.hasMagic(dirPath)) {
                        return resolvedDirs.concat(_glob2.default.sync(dirPath));
                    }
                    return resolvedDirs.concat(dirPath);
                }, []);
            }
        },

how to use autocompletion in IntelliJ/WebStorm?

I use WebStorm of version 2016.3.1 , .babelrc content is

{
    "presets": [
        "react-native"
    ],
    "plugins": [
        "transform-decorators-legacy",
        ["module-resolver", {
        "root": ["./app"],
        "alias": {
          "components": "./app/components",
          "utils":"./app/utils",
          "common":"./app/common",
          "actions":"./app/actions",
          "services":"./app/services"
        }
      }]
    ]
}

when I import a file , path autocompletion does not work.Anyone can help?

babel-runtime is not properly replaced

When you compile the following code:

// The issue occurs only if it's:
//                               
// - function declaration (not function expression or arrow function)
// - export (not export default)

export async function test () {}

with the settings:

"plugins": [
  "trannsform-async-to-generator",
  "transform-es2015-modules-commonjs",
   "transform-runtime",                                                                                                                     
   [
     "module-resolver",
     {
        "alias": {
           "babel-runtime": "./my-babel-runtime"
        }
     }
   ]
]                                                                                                                                               

require call of babel-runtime is wrongly placed to end of the file, so it throws an error when you run the code. I think it can be the issue of babel rather than this plugin, but reported here first anyway.

Original issue was repored here: vercel/next.js#202
You can reproduce the issue with https://github.com/nkzawa/babel-plugin-module-resolver-issue

Babel-register not transpiling module aliased by resolver

My custom module that I set the alias with babel-plugin-module-resolver is not being transpiled by babel-register on dev server. Error that I get is : SyntaxError: Unexpected token import import moment from moment

Directory structure:

- modules 
  - modulex
  - babelrc is not specified
- project-folder
   - src
      - client
      - server
   - .babelrc
 

It is working if I put modules directory under project folder, but I need it outside since I have multiple projects.

- project-folder
   - modules 
      - modulex
   - src
      - client
      - server
   - .babelrc
 

My .babelrc

{
  "presets": ["es2015"],
  "plugins": [
    ["babel-plugin-module-resolver", {
      "root": ["./src"],
      "alias": {
        "modulex": "../modules/modulex"
      }
    }]
  ],
  "ignore": "node_modules"
}

For development I am using babel-register like this:

require('babel-register');
require('./start');

In project code i require dependency to modulex like this
import { formatDate } from 'modulex/src/utils/format';

Version of this plugin that I use is: v2.5.0

At some point this was working. Any ideas?
Cheers
Primoz

Supporting require.resolve

Being a native function, it would make sense to support it. It would allow to read files the nice way:

import { readFileSync } from 'fs';

let readme = readFileSync(require.resolve('some-alias/README.md'));

Expose is not taking path

Hello thanks for this module.

The issue is that expose inside babelrc has to be a single word, not a real path! so as an example

{
  "plugins": [
    ["babel-plugin-module-alias", [
      { "src": "./src/utils", "expose": "Awesome/utils" },
      { "src": "./src/components", "expose": "Awesome/components" }
    ]]
  ]
}

the above configuration causes your module to crash! so what we ended up doing is forked it and added the following code/hack there.

function mapModule(modulePath, state, filesMap) {
    ///HACK
    if (modulePath.startsWith('Awesome')) {
        if (filesMap.hasOwnProperty(modulePath)) {
            return mapToRelative(state.file.opts.filename, filesMap[modulePath]);
        } else {
            return null;
        }
    }
    ///////////////////////////////////

    var moduleSplit = modulePath.split('/');

    if (!filesMap.hasOwnProperty(moduleSplit[0])) {
        return null;
    }

    moduleSplit[0] = filesMap[moduleSplit[0]];
    return mapToRelative(state.file.opts.filename, moduleSplit.join('/'));
}

Do you have any plan to support this feature?

Thanks

doesnt work when packaging your project as npm module

if you publish your package to npm/sinopia type registry

paths specified in "src" become relative to the project root, instead of relative to the .babelrc or package.json of the current module

e.g.

Module A: this works perfectly
{ "src": "/some/path/to/Package.js", "expose": "Package" },

Module A is published to NPM, and installed in Module B
Error: Cannot find module '../../../../src/vendors/apigateway/APIClient.js' from '/Users/halln/git/real/comps/static-mobile-web-redesign/node_modules/api-nodified/src/components'

you'll notice its going up to the project root, instead of being relative to the current modules package.json or .babelrc

Aliasing subfolders possible?

Hi,

I've added this to my plugin settings:

["module-resolver", {
  "alias": {
      "react": "inferno-compat",
      "react-dom": "inferno-compat",
      "react-dom/server": "inferno-compat"
  }
}]

However, I'm getting this error:

Unable to resolve some modules:

"react-dom/server" in /Users/Tim/Development/Test/node_modules/react-mounter/dist/server.js (web.browser)

Is there any way to make this work?

Tim

Unable to properly alias directly from src

I am having a minor issue accessing my components directly from my src folder. Every folder outside of my src files I am able to access via absolute path. I'm not sure exactly what I need to modify to get this working

file structure

- __tests__
- src
  - display
    - component-1-folder
       * index.jsx
    - component-2-folder
       * index.jsx
- .babelrc

From my test folder I can access component 1 via src/display/component-1-folder
However, if I try to access component 1 from the component 2 file I get the Unable to resolve path to module

My .babelrc file is

{
  "presets": ["es2015", "stage-1", "react"],
  "plugins": [
    ["module-resolver", {
      "root": ["./src"],
      "alias": {
        "src": "./src",
      }
    }]
  ]
}

Thanks in advance!

Windows Pathing issue in 1.1

After upgrading to 1.1, I have a issue with pathing in windows. I receive the following:

[09:24:15] Starting 'babel'...
from C:\dev\swimlane\Node\src\server.js
to: C:\dev\swimlane\Node\src
dest: ..\src

{ [TypeError: C:/dev/swimlane/Node/src/config/Application.js: Path must be a string. Received undefined]
  _babel: true,
  name: 'TypeError',
  message: 'C:/dev/swimlane/Node/src/config/Application.js: Path must be a string. Received undefined',
  stack: 'TypeError: C:/dev/swimlane/Node/src/config/Application.js: Path must be a string. Received undefined\n    at assertPath (path.js:8:11)\n    at Object.win32.resolve (path.js:130:5)\n    at mapToRelative (C:\\dev\\swimlane\\Node\\node_modules\\babel-plugin-module-alias\\lib\\index.js:27:42)\n    at mapModule (C:\\dev\\swimlane\\Node\\node_modules\\babel-plugin-module-alias\\lib\\index.js:43:12)\n    at transformImportCall (C:\\dev\\swimlane\\Node\\node_modules\\babel-plugin-module-alias\\lib\\index.js:66:30)\n    at PluginPass.exit (C:\\dev\\swimlane\\Node\\node_modules\\babel-plugin-module-alias\\lib\\index.js:82:28)\n
  at newFn (C:\\dev\\swimlane\\Node\\node_modules\\babel-traverse\\lib\\visitors.js:276:19)\n    at NodePath._call (C:\\dev\\swimlane\\Node\\node_modules\\babel-traverse\\lib\\path\\context.js:74:18)\n    at NodePath.call (C:\\dev\\swimlane\\Node\\node_modules\\babel-traverse\\lib\\path\\context.js:46:17)\n    at NodePath.visit (C:\\dev\\swimlane\\Node\\node_modules\\babel-traverse\\lib\\path\\context.js:116:8)',
  fileName: 'C:\\dev\\swimlane\\Node\\src\\config\\Application.js',
  showStack: false,
  showProperties: false,
  plugin: 'gulp-babel' }

Pathname must be a string in Docker container

When using this plugin (v1.2.0) inside of a Docker container I am running into the "Pathname must be a string. Got undefined" error. This is similar to #15. I can get around this by setting PWD in my Docker environment, but it seems that it should fall back to process.cwd(), which is returning what I expect.

"export from" is not handled

Hi, I had some trouble with one particular file today that looked like this:

export { default as A } from 'dir/a';
export { default as B } from 'dir/b';
export { default as C } from 'dir/c';

It turns out that this plugin does not handle the export from syntax and leaves the paths as they are.

I'd like to fix that, so expect a PR soon 🙂

Plugin compatibility, exit vs enter?

I had trouble composing another module transformation babel plugin I wrote with this module, and I finally boiled it down to the fact that I was using enter and you were using exit (see here).

Its really more of a question than an issue, was there any particular reason to use exit rather than enter for your code? Since this is a relatively simple transformation, would it make sense to perform it as early as possible so that it is easier to compose? Forgive me if this is a silly question, I have very little experience with babel myself.

[Feature Request] Autocompletion

Hello,

this module is super useful and removes the pain of relative paths, so thank you for it !

Before, I used to symlink my local folders to node_modules, so I could have both autocompletion and global module require!

With your plugin, the autocompletion part is lost, so maybe you could add an option (or doing it by default I don't know) to automatically symlink all the aliases inside node_modules, so when working in WebStorm for example, we could have autocompletion. ✨

Example of what I mean :

Project structure :

|-- my-app
|   |-- node_modules
|   |   |-- @my-app
|   |   |   |-- domain <-- symlink to src/domain
|   |   |   |-- foo.js <-- symlink to src/helpers/foo.js
|   |   |   |-- infrastructure <-- symlink to src/infrastructure
|   |   |   |-- user-interface <-- symlink to src/user-interface
|   |   |-- uber-global-stuff <-- symlink to src/uber-global-stuff
|   |-- src
|   |   |-- domain
|   |   |-- helpers
|   |   |   |-- foo.js
|   |   |-- infrastructure
|   |   |-- user-interface
|   |   |-- uber-global-stuff

.babelrc :

{
  "plugins": [
    ["module-alias", [
      { "src": "./src/domain", "expose": "@my-app/domain" },
      { "src": "./src/helpers/foo", "expose": "@my-app/foo" },
      { "src": "./src/infrastructure", "expose": "@my-app/infrastructure" },
      { "src": "./src/user-interface", "expose": "@my-app/user-interface" },
      { "src": "./src/uber-global-stuff", "expose": "uber-global-stuff" }
    ]]
  ]
}

Support for jest.mock()

Hey,

I have following use-case: I'd like to mock require call with Jest testing framework, but when I do it this way:

file.js

// foobar is rewritten to ../../foobar by this plugin
import foobar from 'foobar'

file.test.js

jest.mock('foobar', () => {
  ...
})

then mock is not instatiated, as foobar is rewritten in tested file by this plugin to ../../foobar

Ideally I would be able to do something like this:

jest.mock(require.resolve('foobar'), () => {
  ...
})

and it would translate to:

jest.mock('../../foobar', () => {
  ...
})

what would result in proper require mocks.

Could this plugin support rewriting also require.resolve(XXX)?

import module is undefined

When i require any of my files it gives me undefined;

.babelrc file

{
	"sourceMaps": true,
	"plugins": [
		["module-resolver", {
			"root": ["./src"],
			"extensions": [".js"],
			"alias": {
				"lib": "./lib",
				"modules": "./modules"
			}
		}]
	],
	"presets": ["es2015", "stage-0"],
}

messages.js

import app from 'lib/express';

console.log(app); // app is undefined
export default function (/* messaging */) {

}

Relative paths not correctly resolved when used with babel-register

We want to use this plugin because it is really great, but we couldn't easily get it working our serverside-rendering app.

.babelrc

{
  "presets": [
    "es2015-loose", "stage-1", "react"
  ],
  "plugins": [
    [
      "module-alias",
      [
        { "src": "./src/js-modules/modules", "expose": "modules" }
      ]
    ]
  ]
}

services/v8/serverside.js

...
require('babel-register')({
        only: /src\/js-modules/
    });

When we now try to transform a file with import a from 'modules/abc'; we receive an error:

Error: Cannot find module '../../../../../services/v8/src/js-modules/modules/abc'

So it seems that the paths are not relative to the babelrc file, but to something else. Did we make something wrong?

Not working with React Native Android project (RN 0.42)

I am working on a project with ReactNative version 0.42 for an Android app, using the Android Studio emulator. I have followed the setup instructions and also have a .babelrc file with the following:

// .babelrc
{
  "presets": ["react-native"],
  "plugins": [
    ["module-resolver", {
      "root": ["./src"],
      "alias": {
        "app": "./src/app",
        "assets": "./src/assets"
      }
    }]
  ]
}

No matter what I try, including react-native start -- -reset-cache, I still get the following:

image

Support for React Native

Hey there. This is not an issue per say, more a cry for help.

Have you by some crazy chance attempted to use this plugin with React Native? It simply just doesn't seem to work. I opened a Stack Overflow issue about this. Any help would be greatly appreciated! If you're at a loss as I am, please feel free to ignore and close this issue.

Support package.json browser field

Browserify and I believe webpack support the browser field in the package.json for aliases. Any chance you could as well. I'm all about re-using existing config if possible :)

Help people update from babel-plugin-module-alias

I just read a stackoverflow answer that refer to the old babel-plugin-module-alias when trying to find how to do what this plugin does.. When I installed it, npm told be it was deprecated and to use resolver instead, which I did. However, even after finding this github page, I was a little confused and it took me a bit of trial and error behavior I figured it all out: The original behavior was moved to moved to the "alias" option and that we can now use root to do a similar (possibly better, depending on opinions) trick.

The lack of clear error message was quite annoying as debugging meant relaunching npm each time with cache cleared, which takes a while.

My suggestion is 2-fold:

  • Update the readme to indicate that this change happened. I can propose a pull request if you want, but i'm not quite sure where to put that text and how to word it. Your call.
  • If configured with wrong params, it would be great if it failed with an explanation message (linking to the Github page would be helpful if the point above is done). For example of wrong params: Receiving an array, receiving a hash that contains 'src' or 'expose'. In those 3 cases, it's most likely someone running based on an old version.

Error message idea: You are using an unsupported way of configuring babel-plugin-module-resolver. See https://github.com/tleunen/babel-plugin-module-resolver for details on the changes.

Regards

Differences between Windows vs. POSIX

Hi,

It looks like there are differences between Windows and POSIX paths, and if somehow you build a project on Windows and want to run it in a Linux environment, it fails with Error: Cannot find module.

I see that there are more ways in which the paths are actually written in the files:
import api from 'modules/api'; => var _api = require('./modules\\api');
import apiServices from 'services/api' =>var _apiServices = require('....\services\api');`

The mappings are:

      "module-alias", [
        { "src": "./src/js/modules", "expose": "modules" },
        { "src": "./src/js/services", "expose": "services" }
      ]

Is there any way to override the Windows styles and make sure that POSIX style will always be used?

Raul.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.