How to change relative paths to absolute paths for imports
Context
I have a React project set up using webpack, eslint, flow and jest. Here is a documentation of the places that require configurations for getting the absolute paths working.
Problem
// what we wantimport reducer from 'reducer';// what we don't wantimport reducer from '../../../reducer';
Configurations
Webpack
https://gist.github.com/sokra/27b24881210b56bbaff7#resolving-options
// webpack.config.jsresolve: { modules: [path.resolve(__dirname, './src'), 'node_modules'], extensions: ['.js', '.jsx', '.json'], alias: { reducers: path.resolve(__dirname, './src/reducers') }},
Eslint
> npm install eslint-import-resolver-webpack eslint-plugin-import -D
https://github.com/benmosher/eslint-plugin-import/issues/496
// .eslintrc "settings": { "import/resolver": { "webpack": { "config": "webpack.config.js" } }},
Flow
https://github.com/facebook/flow/issues/101
// .flowconfigmodule.name_mapper='^reducers\/\(.*\)$' -> '<PROJECT_ROOT>/src/reducers/\1'module.name_mapper='^reducers$' -> '<PROJECT_ROOT>/src/reducers'module.system.node.resolve_dirname='<PROJECT_ROOT>/src/'
Jest
Our tests do not go through webpack transformation and therefore will not recognize the absolute path aliases if we have configured this in webpack only.
Since Jest tests go through Babel for transpile, we can use a babel module resolver to resolve the relative directives into absolute paths.
https://github.com/tleunen/babel-plugin-module-resolver
// .babelrc{"plugins": [ ["module-resolver", { "root": ["./src"], "alias": { "test": "./test", "reducers": "./src/reducers" } }] ]}