Code Monkey home page Code Monkey logo

babel-plugin-webpack-alias's Introduction

babel-plugin-webpack-alias

This Babel 6 plugin allows you to use webpack aliases and most of webpack resolve features in Babel.

Travis build Appveyor build codecov Gemnasium

Stable version Downloads semantic-release Commitizen friendly

This plugin is simply going to take the aliases defined in your webpack config and replace require paths. It is especially useful when you rely on webpack aliases to keep require paths nicer (and sometimes more consistent depending on your project configuration) but you can't use webpack in a context, for example for unit testing.

If you are having issues while making this plugin work, have a look at the examples folder. Play with them, mix your own config in, and feel free to open an issue!

Example

With the following webpack.config.js:

module.exports = {
    ...
    resolve: {
        alias: {
            'my-alias': path.join(__dirname, '/alias-folder/js/'),
            'library-name': './library-folder/folder'
        }
    }
    ...
};

A javascript file before compilation:

var MyModule = require('my-alias/src/lib/MyModule');
import MyImport from 'library-name/lib/import/MyImport';

will become:

var MyModule = require('../../alias-folder/js/lib/MyModule');
import MyImport from '../../library-folder/folder/lib/import/MyImport';

This is an example but the plugin will output the relative path depending on the position of the file and the alias folder.

See the examples folder for more configuration examples.

Installation

$ npm install --save-dev babel-plugin-webpack-alias

Add it as a plugin to your .babelrc file. You can optionally add a path to a config file, for example:

{
   "presets":[ "react", "es2015", "stage-0" ],
   "env": {
    "test": {
      "plugins": [
        [ "babel-plugin-webpack-alias", { "config": "./webpack.config.test.js" } ]
      ]
    }
  }
}

In this case, the plugin will only be run when NODE_ENV is set to test.

Supported resolve options

  • resolve.alias: That is the reason why this plugin has been made, see above for examples and details.
  • resolve.extensions: It will try to match extensions provided in the webpack configuration.

Options

  • config(string): Path to your webpack config file.

    The plugin is going to look for a webpack.config.js file or a webpack.config.babel.js at the root, in case your webpack configuration file is in another location, you can use this option to provide an absolute or relative path to it. You can also use environment variable in this option, using lodash template, for example:

    {
       "presets":[ "react", "es2015", "stage-0" ],
       "env": {
        "test": {
          "plugins": [
            [ "babel-plugin-webpack-alias", {
                "config": "${PWD}/webpack.config.test.js"
              }
            ]
          ]
        }
      }
    }

    And run with:

    $ PWD=$(pwd) NODE_ENV=test ava
  • findConfig(boolean): Will find the nearest webpack configuration file when set to true.

    It is possible to pass a findConfig option, and the plugin will attempt to find the nearest webpack configuration file within the project using find-up. For example:

    {
       "presets":[ "react", "es2015", "stage-0" ],
       "env": {
        "test": {
          "plugins": [
            [ "babel-plugin-webpack-alias", {
                "config": "webpack.config.test.js",
                "findConfig": true
              } ]
          ]
        }
      }
    }
  • noOutputExtension(boolean): Don't append extension at the end of filenames even when a resolve.extensions webpack config is set.

    The normal behaviour of the resolve.extensions support is this one:

    var MyModule = require('my-alias/src/lib/MyComponent.jsx');
    // is converted to:
    var MyModule = require('../../alias-folder/js/lib/MyComponent.jsx');

    However in particular cases you'll compile MyComponent.jsx to a MyComponent.js file so the build alias won't be able to resolve the jsx file. In that case you can turn noOutputExtension on and get:

    var MyModule = require('my-alias/src/lib/MyComponent.jsx');
    // is converted to:
    var MyModule = require('../../alias-folder/js/lib/MyComponent');

babel-plugin-webpack-alias's People

Contributors

adriantoine avatar amilajack avatar greenkeeperio-bot avatar kellycampbell avatar luke-john avatar montmanu avatar snadn avatar wmertens 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  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

babel-plugin-webpack-alias's Issues

Cannot find module "..." when module is immediately used

This is probably related to #5.

The following will fail with Error: Cannot find module '../higher-order/activateable':

import Activateable from 'ui/higher-order/activateable';

const SectionElement = Activateable("section")

If I add the extension to activeatable, it works:

import Activateable from 'ui/higher-order/activateable.jsx';

const SectionElement = Activateable("section")

Resolved config doesn't contain a resolve configuration

I've seen this issue in a closed github issue, but I just installed v2.0.0 of this plugin and received the same issue. Here are my configs for reference:

Webpack.config

const config = Object.assign({
    entry: entryPoint,
    output: {
        filename: outputFileName,
        library: libraryName,
        libraryTarget: 'umd',
        umdNamedDefine: true
    },
    module: {
        loaders: [{
            test: /\.(jsx|js)$/,
            exclude: /(node_modules)/,
            loader: 'babel',
            query: {
                presets: ['es2015', 'react'],
                plugins: ['transform-object-rest-spread', 'transform-class-properties']
            }
        }, {
            test: /\.(styl|css)$/,
            loader: 'style-loader!css-loader!postcss-loader!stylus-loader'
        }, {
            test: /\.(woff2|woff|eot|ttf|svg|otf|png|jpg|jpeg)$/,
            exclude: /(node_modules)/,
            loader: 'url-loader'
        }]
    },
    postcss: function () {
        return [require('autoprefixer')({
            browsers: [
                'last 2 versions'
            ]
        })];
    },
    resolve: {
        alias: {
            'jquery-ui': 'jquery-ui/ui/widgets',
            'sharedScript': path.resolve('./shared/script')
        },
        extensions: ['', '.jsx', '.js', '.styl']
    },
    plugins: [new webpack.DefinePlugin({
        'process.env': {
            NODE_ENV: '"development"',
            UNITY_ENV: '"production"', // If you're building a DEV build from the Unity interface, change this to "development",
            BUILD_VERSION: '"' + readVersionNumber(args) + '"',
            JAVASCRIPT_INTERFACE_NAME: '"' + (buildForRP ? 'ProspectorJavascriptInterface' : 'OnsightJavascriptInterface') + '"',
            LIBRARY_NAME: '"' + libraryName + '"'
        }
    })]
}, production ? {
    plugins: [new webpack.optimize.UglifyJsPlugin({
        compress: {
            sequences: true,
            booleans: true,
            warnings: false,
            drop_debugger: true,
            drop_console: true
        },
        mangle: {
            except: ['$']
        },
        comments: false
    }), new webpack.DefinePlugin({
        'process.env': {
            NODE_ENV: '"production"',
            UNITY_ENV: '"production"', // If you're building a DEV build from the Unity interface, change this to "development",
            BUILD_VERSION: '"' + readVersionNumber(args) + '"',
            JAVASCRIPT_INTERFACE_NAME: '"' + (buildForRP ? 'ProspectorJavascriptInterface' : 'OnsightJavascriptInterface') + '"',
            LIBRARY_NAME: '"' + libraryName + '"'
        }
    })]
} : {});

module.exports = config;
package.json babel config
"babel": {
    "presets": [
      "es2015",
      "react"
    ],
    "plugins": [
      "transform-object-rest-spread",
      "transform-class-properties",
      ["babel-plugin-webpack-alias", { "config": "./webpack.config.js", "findConfig": true }]
    ]
  }

Error, for reference

throw err;
        ^

Error: D:/web/webpack.config.js: The resolved config file doesn't contain a resolve configuration

Example using mocha?

hi, this plugin looks like it does exactly what i need. unfortunately i can't get it to go with mocha :-/

my npm test that runs mocha looks like this:
BABEL_DISABLE_CACHE=1 NODE_ENV=test mocha 'src/**/*.spec.js' --recursive --compilers js:babel-register --require ./src/lib/testsetup.js --require ignore-styles

and my .babelrc looks like this:

{
  "presets": ["es2015", "stage-0", "react"],
  "env": {
    "test": {
      "plugins": [
        [
          "babel-plugin-webpack-alias",
          { "config": "./webpack.config.babel.js" }
        ],
        [
          "babel-plugin-webpack-loaders",
          {
            "config": "./webpack.config.babel.js",
            "verbose": false
          }
        ]
      ]
    }
  }
}

my webpack resolve-section:

    resolve: {
      alias: {
        src: __dirname + '/src',
        shared: __dirname + '/src/components/shared'
      }
    }

i tried this for importing:

import bla from 'shared/bla'
import bla from 'shared/bla.js'

both fails unfortunately with Error: Cannot find module 'shared/bla.js'

what am i doing wrong? working example using mocha would be awesome :)

Proper error reporting if there are issues with webpack config

Had faced an issue when i forgot to put comma to seperate webpack alias, and every time i tried running the babel with babel-plugin-webpack-alias it failed with the following error.

error

SyntaxError: src/server/__test__/models.tokens.specs.js: Unexpected identifier
undefined

webpack config

resolve : {
    extensions: ['','.js','.jsx'],
    modules : [srcPath,path.join(basePath,'./node_modules')],
    alias : {
      config : path.join(basePath,'./config'),
      controller : path.join(srcPath,'./controller'),
      models : path.join(srcPath,'./models'),
      template: path.join(srcPath,'./template') // comma was missing which caused the error
      helpers: path.join(srcPath,'./helpers')
    },
  }

Support resolve.root

Could this plugin be made to support resolve.root? Is there a way to consider it now?

The way I'm doing it now is grabbing my aliases off of my webpack config and prepending the root to them for the aliases I pass to this plugin.

Update readme

Now the plugin not only support webpack aliases, but resolve.extensions, webpack configuration as an array and the option noOutputExtension has to be documented as well.

don't work

webpack.config.js:

alias: {
	'react-df': path.join(__dirname, 'src/react-df.js'),
}

.babelrc:

	"env": {
		"test": {
			"plugins": [
				"babel-plugin-webpack-alias", { "config": "./webpack.config.js" }
			]
		}

xxx.test.js:

import df from 'react-df'
......

when i run with cmd: "set NODE_ENV=test && mocha --compilers js:babel-register test/**/*.test.js"
the error message is "Cannot find module 'react-df'"

new:
i try to change .babelrc to

"plugins": [
	"webpack-aliases"
]

it work! ,however i put it in the env as

	"env": {
		"test": {
			"plugins": [
				"webpack-aliases"
			]
		}
	},

it don't work,
i add a log in test.js, the process.env.NODE_ENV is test.
why it don't work?

Support for Babel 7

Babel 7 is currently in Alpha 9, and this plugin just silently fails.

Seems the CallExpression is never called.

Is support in the pipeline/planned?

Support resolveLoader.alias

I'm trying to change a resolver for a test. Specifically, I have a file being required via "worker-loader?inline=true!pdfjs-dist/build/pdf\.worker", and I would like my test suite to treat it as "raw-loader!pdfjs-dist/build/pdf\.worker".

I tried to abuse the current setup like so:

resolve: {
  alias: {
    "worker-loader\\?inline=true!pdfjs-dist/build/pdf\\.worker": path.resolve(__dirname, "node_modules/pdfjs-dist/build/pdf.worker.js")
  }
}

Unfortunately, that simply prefixes the import with "./", changing it into "./worker-loader?inline=true!pdfjs-dist/build/pdf\.worker".

Webpack config not found when using es6 export statement

In webpack.config.babel.js

If I use:

export default {
 // webpack config properties
}

babel-plugin-webpack-alias's getConfig fails because it needs to reference default (as of Babel 6)

Perhaps checking the __esModule could help determine if we should use default

function getConfig(configPath, findConfig) {
    var conf;
    if(!findConfig) {
        // Get webpack config
        conf = require(resolve(process.cwd(), configPath));
    } else {
        conf = require(findUp.sync(configPath));
    }
    if (conf && conf.__esModule) {
        conf = conf.default
    }
    return conf;
}

Skip preserving file extension for generated path

Babel would emit the files with js extension irrespective of the extension of source files, which would cause problem to test individual files without using webpack or gulp, since required modules path would never be resolved, becuase generated files would have an extension of js and the generated webpack alias path would be referring to jsx(i.e original extension)

I've shown an example to support the use case

.babelrc

{
  "presets": ["es2015", "react","stage-2"],
  "plugins" : [
  ["babel-plugin-webpack-alias", { "config": "./webpack/server/server.js" }]
  ],
}

webpack config

resolve : {
    extensions: ['','.js','.jsx'],
    modules : [srcPath,path.join(basePath,'./node_modules')],
    alias : {
      template: path.join(srcPath,'./template')
    },
  },

es6 code

import Layout from 'template/Layout';

Generating es5 file post babel transformation

src/server/template/Layout.jsx -> lib/server/template/Layout.js

Post babel transformation

var _Layout = require('./Layout.jsx'); //should be './Layout.js'
var _Layout2 = _interopRequireDefault(_Layout);

Running in node

Error: Cannot find module './Layout.jsx'

Support require.resolve

I use this plugin in mocha tests. it's nice to resolve the path with alias when I use require() or import. But I have some special requirements that I need to use the alias path be a parameter for a function mock-require(). Obviously, it doesn't work. Maybe in some cases, we can use require.resolve() to get the real path corresponds to the alias. Thanks for your works, it's awesome!

Unable to resolve correct file path

Hey, Awesome library! Recently however, I've been encountering some issues with it, where the tests are not able to resolve the correct file path for the given alias. For instance, I'm seeing

> cd client && npm run test --silent

module.js:327
    throw err;
    ^

Error: Cannot find module 'node_modules/react/react'
    at Function.Module._resolveFilename (module.js:325:15)
    at Function.Module._load (module.js:276:25)
    at Module.require (module.js:353:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous> (MyTestComponent.jsx:1:1)
    at Module._compile (module.js:409:26)
    at loader (..../client/node_modules/babel-core/node_modules/babel-register/lib/node.js:148:5)
    at Object.require.extensions.(anonymous function) [as .jsx] (..../client/node_modules/babel-core/node_modules/babel-register/lib/node.js:158:7)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Module.require (module.js:353:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous> (MyTestComponent.spec.jsx:4:1)
    at Module._compile (module.js:409:26)
    at loader (..../client/node_modules/babel-core/node_modules/babel-register/lib/node.js:148:5)
    at Object.require.extensions.(anonymous function) [as .jsx] (..../client/node_modules/babel-core/node_modules/babel-register/lib/node.js:158:7)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Module.require (module.js:353:17)
    at require (internal/module.js:12:17)
    at ..../client/node_modules/mocha/lib/mocha.js:220:27
    at Array.forEach (native)
    at Mocha.loadFiles (..../client/node_modules/mocha/lib/mocha.js:217:14)
    at Mocha.run (..../client/node_modules/mocha/lib/mocha.js:469:10)
    at Object.<anonymous> (..../client/node_modules/mocha/bin/_mocha:404:18)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Function.Module.runMain (module.js:441:10)
    at startup (node.js:139:18)
    at node.js:974:3

In the webpack alias, this is defined as

resolve: {
    extensions: ['', '.js', '.jsx'],
    alias: {
      ...
      react: path.resolve('./node_modules/react'),
    },
  },

When this gets compiled in development, it's able to detect the right path, however in test, it looks like the path is wrong, as this is in a nested subfolder, that looks like

- client
  - app
    - bundles
      - MyBundle
        - components
          - MyComponent
            - MyComponent.jsx

so I think the path should actually be more like ./../../../../../node_modules/react/react rather than just node_modules/react/react. When I manually update this path to reflect that, it's able to find the module as intended.

I'm not entirely sure that this is a problem of this package, as this has worked for us in the past, and now it isn't. However, any insights here, would be greatly appreciated.

Working with Ava?

Hi there,

This plugin looks great and is exactly what I need to use with Ava. Unfortunately I cannot get it to resolve my alias correctly. Here is the code, let me know your thoughts.

In the webpack.config.babel.js:

const SRC_DIR = path.join(__dirname, '../src');
....  
resolve: {
        alias: {
            '~': SRC_DIR
        }
    }

In the .babelrc

         [ 
          "babel-plugin-webpack-alias",
          { "config": "../build/webpack.config.babel.js" }
         ]

In my package.json I'm also requiring

"require": [
      "babel-register",
      "ignore-styles"
    ]

Got any ideas? It still is throwing that it can't resolve with that alias.

Can't resolve  ~/components/...

Path must be a string. Received undefined

Not sure what I'm missing to get this to work.

Error:

app/ui/src/utils/api.js: Path must be a string. Received undefined

api.js

import { domain } from 'config'

.babelrc

{
  "env": {
   "development": {
     "plugins": [
        [ "babel-plugin-webpack-alias", { "config": "./webpack.config.js" } ]
      ]
    }
  }
}

webpack.config.js

var path = require('path')
var webpack = require('webpack')

module.exports = {
  devtool: 'eval',
  entry: [
    'webpack-dev-server/client?http://localhost:3000',
    'webpack/hot/only-dev-server',
    './src/index',
  ],
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js',
    publicPath: '/static/',
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
  ],
  module: {
    loaders: [
      {
        test: /\.js$/,
        loaders: [ 'react-hot', 'babel' ],
        include: path.join(__dirname, 'src'),
      },
      { test: /\.styl$/, loader: 'style-loader!css-loader!stylus-loader' },
    ],
  },
  resolve: {
    root: path.resolve(__dirname),
     alias: {
       config: path.join(__dirname, 'config', process.env.NODE_ENV),
     },
     extensions: ['', '.js', '.styl'],
  },
  node: {
    fs: 'empty',
    net: 'empty',
    tls: 'empty',
    bufferutil: 'empty',
  },
}

Not currently working at all with ava

Dependencies

"ava": "^0.16.0",
"babel-core": "^6.18.2",
"babel-plugin-webpack-alias": "^2.1.2",
"webpack": "^1.13.3"

Babel config

{
	"only": [
		"*.js",
		"*.test.js",
		"*.babel.js"
	],
	"ignore": [
		"./node_modules",
		"./node_modules/**/node_modules"
	],
	"presets": ["react", "es2015", "es2016", "stage-0"],
	"plugins": [
		"transform-object-rest-spread",
		["webpack-alias", {
			"config": "${PWD}/config/webpack/development.js"
		}]
	],
	"env": {
		"development": {
			"plugins": [
				"transform-class-properties",
				"react-hot-loader/babel"
			]
		},
		"test": {
			"plugins": [

			]
		}
	}
}

Webpack config

/* eslint-disable */
var webpack = require('webpack');
var path = require('path');
var BundleTracker = require('webpack-bundle-tracker');
var ROOT_PATH = path.resolve(__dirname, '..', '..');
var ExtendedDefinePlugin = require('extended-define-webpack-plugin');
var apiSettings = require('./common').API_CONFIG['development'];
var appSettings = require('./common').APP_CONFIG['development'];

module.exports = {
	debug: true,
	devtool: 'eval-source-map',
	entry: [
		'webpack-hot-middleware/client',
		'webpack/hot/only-dev-server',
		'babel-polyfill',
		path.resolve(ROOT_PATH, 'src', 'client', 'index')
	],
	output: {
		path: path.resolve(__dirname, '/'),
		publicPath: 'http://localhost:8080/static/',
		filename: 'client.js'
	},
	module: {
		loaders: [
			{
				test: /\.css$/,
				loader: 'style-loader!css-loader'
			},
			{
				test: /\.js$/,
				exclude: [/node_modules/],
				loaders: ['babel']
			}
		]
	},
	resolve: {
		alias: {
			'seeds': path.resolve(ROOT_PATH, 'seeds'),
			'client/containers': path.join(ROOT_PATH, 'src', 'client', 'containers'),
			'client/actions': path.join(ROOT_PATH, 'src', 'client', 'actions'),
			'client/middleware':  path.join(ROOT_PATH, 'src', 'client', 'middleware'),
			'client/routes':  path.join(ROOT_PATH, 'src', 'client', 'routes'),
			'client/store': path.join(ROOT_PATH, 'src', 'client', 'store'),
			'client/sagas': path.join(ROOT_PATH, 'src', 'client', 'sagas'),
			'client/utils':  path.join(ROOT_PATH, 'src', 'client', 'utils'),
			'client/reducers': path.join(ROOT_PATH, 'src', 'client', 'reducers'),
			'server/utils':  path.join(ROOT_PATH, 'src', 'server', 'utils'),
		},
		extensions: ['.js', '']
	},
	plugins: [
		new webpack.HotModuleReplacementPlugin(),
		new webpack.NoErrorsPlugin(),
		new ExtendedDefinePlugin({
			'process.env': {
				'NODE_ENV': 'development'
			},
			API_SETTINGS: apiSettings,
			APP_SETTINGS: appSettings,
			__DEVELOPMENT__: true,
			__PRODUCTION__: false,
			__DEVTOOLS__: true
		}),
		new BundleTracker({
			path: ROOT_PATH,
			filename: './webpack-stats.json'
		})
	],
};

AVA config

"ava": {
    "files": [
      "__tests__/**/*.js"
    ],
    "concurrency": 5,
    "failFast": true,
    "tap": true,
    "powerAssert": true,
    "require": [
      "babel-register"
    ],
    "babel": "inherit"
  }

Project Structure

- __tests__
    - reducers
        - app.js
    - selectors
        - transactions.js
- config
- seeds
- src
    - client
        - actions
            App.js
            index.js
            Segment.js
            Session.js
        ...
        ...
        ...

Test Script
"PWD=$(pwd) NODE_ENV=test BABEL_DISABLE_CACHE=1 ava --serial --verbose --tap | tap-nyan"

Error

Error: Cannot find module 'client/actions/App'
    at Function.Module._resolveFilename (module.js:440:15)
    at Function.Module._load (module.js:388:25)
    at Module.require (module.js:468:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/Users/joeyfigaro/work/projects/app/__tests__/reducers/app.js:5:1)
    at Module._compile (module.js:541:32)
    at extensions.(anonymous function) (/Users/joeyfigaro/work/projects/app/node_modules/require-precompiled/index.js:13:11)
    at Object.require.extensions.(anonymous function) [as .js] (/Users/joeyfigaro/work/projects/app/node_modules/ava/lib/test-worker.js:92:3)

It doesn't look like it's even using the webpack config - if I add console.log() to my config, nothing shows up when I run my test script. I've attempted to move the webpack config to root and have tried renaming it to the default name the plugin looks for to no avail.

Have I missed something obvious here?

how to have flow resolve the aliases ?

Flow error

Launching Flow server for /Users/florian/Code/Public/PlanetX/boilerplate-crater
Spawned flow server (pid=54050)
Logs will go to /private/tmp/flow/zSUserszSflorianzSCodezSPubliczSPlanetXzSboilerplate-crater.log
src/universal/routes/home.js:2
  2: import type { Store } from 'universal/flowtypes/redux'
                                ^^^^^^^^^^^^^^^^^^^^^^^^^^^ universal/flowtypes/redux. Required module not found

resolve portion of my webpack config

import path from 'path'
const root = path.resolve(__dirname, '..')

const aliases = {
  client   : `${root}/src/client`,
  modules  : `${root}/src/modules`,
  routes   : `${root}/src/universal/routes`,
  server   : `${root}/src/server`,
  universal: `${root}/src/universal`
}

const resolve = {
  extensions: ['.js', '.jsx'],
  alias     : aliases
}

export default resolve

.babelrc

  "env": {
    "dev": {
      "plugins": [
        [ "babel-plugin-webpack-alias", { "config": "./webpack/webpack.config.dev.js" } ]
      ]
    },
    "prod": {
      "plugins": [
        [ "babel-plugin-webpack-alias", { "config": "./webpack/webpack.config.prod.js" } ]
      ]
    },

package.json

{
  "dependencies": {
    "babel-runtime": "^6.11.6",
    "bcrypt": "^1.0.2",
    "debug": "^2.5.2",
    "es6-promisify": "^5.0.0",
    "express": "^4.14.0",
    "immutable": "^3.8.1",
    "meteor-node-stubs": "^0.2.6",
    "react": "^15.5.4",
    "react-dom": "^15.5.4",
    "react-dom-stream": "^0.5.1",
    "react-redux": "^5.0.4",
    "react-router": "^3.0.5",
    "react-router-redux": "^4.0.8",
    "redux": "^3.5.2",
    "redux-immutablejs": "0.0.8"
  },
  "devDependencies": {
    "assets-webpack-plugin": "^3.5.1",
    "async-child-process": "^1.1.1",
    "babel-cli": "^6.24.1",
    "babel-core": "^6.24.1",
    "babel-eslint": "^7.2.3",
    "babel-loader": "^6.4.1",
    "babel-plugin-add-module-exports": "^0.2.1",
    "babel-plugin-istanbul": "^3.1.2",
    "babel-plugin-meteor-imports": "^1.0.3",
    "babel-plugin-module-resolver": "^2.7.0",
    "babel-plugin-transform-decorators-legacy": "^1.3.4",
    "babel-plugin-transform-object-rest-spread": "^6.23.0",
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-plugin-webpack-alias": "^2.1.2",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-es2015-node5": "^1.2.0",
    "babel-preset-es2017": "^6.24.1",
    "babel-preset-flow": "^1.0.0",
    "babel-preset-react": "^6.24.1",
    "babel-preset-stage-1": "^6.24.1",
    "babel-register": "^6.24.1",
    "chai": "^3.5.0",
    "coveralls": "^2.13.0",
    "crater-util": "^1.2.2",
    "cross-spawn": "^5.1.0",
    "css-loader": "^0.28.0",
    "dotenv": "^3.0.0",
    "empty": "^0.10.1",
    "es6-promise": "^4.1.0",
    "eslint": "^3.19.0",
    "eslint-config-planetx": "^0.1.7",
    "eslint-import-resolver-babel-module": "^3.0.0",
    "eslint-watch": "^3.1.0",
    "extract-text-webpack-plugin": "^2.1.0",
    "file-loader": "^0.9.0",
    "flow-bin": "^0.44.2",
    "flow-typed": "^2.1.2",
    "flow-watch": "^1.1.1",
    "glob": "^7.1.1",
    "happypack": "^3.0.3",
    "http-proxy": "^1.16.2",
    "istanbul": "^0.4.5",
    "json-loader": "^0.5.4",
    "meteor-imports-webpack-plugin": "^2.0.4",
    "mkdirp": "^0.5.1",
    "mocha": "^3.2.0",
    "node-inspector": "^0.12.10",
    "nyc": "^8.4.0",
    "phantomjs-prebuilt": "^2.1.14",
    "postcss-loader": "^0.13.0",
    "postcss-modules-values": "^1.2.2",
    "pre-commit": "^1.2.2",
    "progress-bar-webpack-plugin": "^1.9.3",
    "raw-loader": "^0.5.1",
    "react-hot-loader": "^3.0.0-beta.6",
    "redux-logger": "^2.10.2",
    "rimraf": "^2.6.1",
    "smart-restart": "^1.1.1",
    "style-loader": "^0.13.2",
    "url-loader": "^0.5.8",
    "wdio-mocha-framework": "^0.5.10",
    "wdio-phantomjs-service": "^0.2.2",
    "wdio-spec-reporter": "^0.1.0",
    "webdriverio": "^4.7.1",
    "webpack": "^2.4.1",
    "webpack-dev-middleware": "^1.10.2",
    "webpack-hot-middleware": "^2.18.0",
    "webpack-node-externals": "^1.5.4"
  }
}

Webpack 2: No config found when config is a function

Webpack 2 supports exporting a default function as the webpack config.

export default env => {
    // return env-specific configuration
}

I'm using this for the reasons in this post.

babel-plugin-webpack-alias will need to check for a function, invoke it (potentially with the value env), to get the config object, before it checks if config.resolve exists

Otherwise you get the 'The resolved config file doesn\'t contain a resolve configuration' error

The support for trailing $

Hi!

In the webpack docs for resolve.alias there is an option to resolve a specific file by doing this:

resolve: {
    alias: { xyz$: 'path/to/xyz.js' }
}

, and then using it in the code like

import xyz from 'xyz'

However, that does not work with the plugin.
What does work is to have a webpack config like this:

resolve: {
    alias: { xyz: 'path/to/xyz.js' }
}

, and using it like this:

import xyz from 'xyz'

This is caused by the following line in the src/index.js:176, I think:

let requiredFilePath = filePath.replace(aliasFrom, relativeFilePath);

I can submit a pr, but I'm just not sure what kind of behavior is expected.
Maybe the correct way is checking if aliasFrom ends with $, and, in case it does and the path starts with aliasFrom.slice(1), do filePath.replace(aliasFrom.slice(1), relativeFilePath), so the module remains backward compatible?
Or just add the description of the workaround to the README.md?

Optionally allow the path to be specified to be relative to where babel was ran

Currently the path being passed in to the "config" option seems to be relative to the current working directory.

In my use case, I need the path to be relative to where the command was run, as I am using this plugin with ava which appears to set the current working directory to the path of the test file being run.

Would it be possible to add some sort of option, for example "relative": true for this?

Does not seem to work with babel

Love this plugin. However I seem to be having some issues with the plugin/preset run ordering... Given the following .babelrc file:

{
  "presets": ["react", "es2015", "stage-0"],
  "plugins": [
    [ "webpack-alias", { "config": "${PWD}/webpack.config.babel.js" } ]
  ],
  "ignore": [
    "dist/*"
  ]
}

I get the following error when running babel src -d dist in my terminal:

Unexpected token import

What's weird though is if I remove the webpack-alias plugin, everything compiles correctly. Interestingly, if I use webpack-alias with node-babel, it also works. Only when I use babel from the babel-cli package do I get the error.

Relative paths don't work when not prefixed with ./

From @vpotravnyy

We're using babel-plugin-webpack-alias for running our tests in Mocha without full build.
Today it stopped work for us after dependencies update
Upon running tests we've got such error: Error: Cannot find module 'actions/api' throwing from very first test

Here's resolve part of our config:

var path = require('path')

module.exports = {
   "resolve":{
      "root": path.resolve(__dirname),
      "modulesDirectories":[
         "node_modules",
         "actions",
         "components",
         ...
      ],
      "alias":{
         "commonActions":"actions",
         "apiActions":"actions/api",,
         "customFormActions":"actions/formCustom",
         "components":"components",
         "formComponents":"components/form",
         ...
      },
      "extensions": ['', '.json', '.js', '.jsx']
   },
   ...
}

P.S. We finished up in approach from first comment: create separate test config with absolute paths for aliases. That works for us but may confuse other users of this library

At the moment if your relative paths are not prefixed with ./, it won't work because of those lines brought for private modules support.

Issue with 1.8.3 release

The 1.8.3 release is broken, as pointed out here and here.

I have just published a 1.8.4 version that looks exactly like 1.8.2.

If you have the error message:

The resolved config file doesn't contain a resolve configuration

please upgrade to 1.8.4!

Sorry for the inconvenience, I still have to address this issue as it's a weird one!

Support resolve.extensions

Would be nice to be able to do the following:

const Nav = require('ui/components/navigation')
// instead of 
const Nav = require('ui/components/navigation.jsx')

Jest compatibility?

Hi! Thanks for sharing this project! I'm trying to use it with Jest, and running into trouble:

myproject-consumer-portal feature/test-architecture ✗ 3h26m △ ➜ yarn test
yarn test v0.24.6
$ jest
 FAIL  src/modules/client/ducks/flow/reducers.spec.js
  ● Test suite failed to run

    /Users/brandon/code/myproject-consumer-portal/src/modules/client/ducks/flow/reducers.spec.js: Unexpected token import

      at createScript (vm.js:53:10)
      at Object.runInThisContext (vm.js:95:10)
      at Module._compile (module.js:543:28)
      at Object.Module._extensions..js (module.js:580:10)
      at Module.load (module.js:488:32)
      at tryModuleLoad (module.js:447:12)
      at Function.Module._load (module.js:439:3)
      at Module.require (module.js:498:17)
      at require (internal/module.js:20:19)
      at PluginPass.CallExpression (node_modules/babel-plugin-webpack-alias/build/index.js:39:28)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        1.607s
Ran all test suites.
error Command failed with exit code 1.

I'm digging into the source trying to figure out how to work around it, but I don't have any good leads yet. If anyone has ideas, I'd love to hear them! :-)

My .babelrc:

{
	"presets": ["react", "es2015", "stage-1"],
	"plugins": [
		"add-module-exports",
		"jsx-display-if",
		"transform-class-properties",
		"transform-object-rest-spread",
		[ "babel-plugin-webpack-alias", { "config": "./tools/webpack/webpack.resolve.babel.js", "findConfig": true } ],
		"styletron-react"
	]
}

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.