I'm setting up my build script in order to do server-side rendering on some routes of my web app. I'm using React and Firebase. Right now, my project structure is.
root
> buildScripts // Some build scripts to replace some import paths
> functions
> distApp // React app files (src folder down below) transpiled to Node v10
> distFunctions // Cloud functions files transpiled to Node v10
function1.js
> src // Cloud functions files written in ES6
function1ES6.js
index.js // indexES6 transpiled to Node v10
indexES6.js // index.js written in ES6
package.json // Dependencies for functions
> src // React app files written in ES6
firebase.json // Firebase configuration
package.json // Dependencies for client
What I'm planning to do as my build flow:
functions/src
to functions/distFunctions
.functions/indexES6.js
to functions/index.js
root/src
to functions/distApp
(THAT'S MY CURRENT PROBLEM)
I end up using some path aliases to make some imports
throughout my App a little bit clearer. Like the ones listed below:
jsconfig.json
"paths": {
"@components/*": ["./src/components/*"],
"@constants/*": ["./src/constants/*"],
"@helpers/*": ["./src/helpers/*"]
}
And when I'm building to production (client browser code) I'm dealing with those paths with Webpack. I add a resolve
property so Webpack knows how to handle them. And bundles it correctly.
webpack.config.js
resolve: {
alias: {
'@components': path.resolve(__dirname, 'src/components'),
'@constants': path.resolve(__dirname, 'src/constants'),
'@helpers': path.resolve(__dirname, 'src/helpers')
}
}
So Webpack knows how to resolve and replace those imports. But Babel does NOT.
Then, when I'm transpiling all of my app files in my root/src
folder to my functions/distApp
. Babel keeps those imports untouched. require('@components/something');
And, as expected, my functions
code have no idea to where @components
resolves to.
QUESTION
How can I access those imports
during the Babel transpiling process and update them? Is there a plugin that could do that? How can I handle this?
PS: I would like to keep using path aliases, because deep files importing shallow files can get pretty ugly. Like import helper from '../../../../../../../helpers/someHelper';
. And when I import like that, if I move the file around, I break the import immeadiately, whilst import helper from '@helper/someHelper'
does not break at all.
You can use https://www.npmjs.com/package/babel-plugin-module-resolver
plugin and specify aliases there, almost in the same way you did it in jsconfig.json
, but in .babelrc
file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With