我正在设置构建脚本,以便在我的web应用程序的某些路由上进行服务器端渲染。我正在使用React和Firebase。现在,我的项目结构如下:
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
我计划的构建流程如下:
- 将 ES6 格式的函数文件转译到 Node v10 环境。从
functions/src
到functions/distFunctions
。 - 将
functions/indexES6.js
转译为functions/index.js
- 将 App 文件从
root/src
转译到functions/distApp
(这是我的当前问题)
我最终使用了一些路径别名,使得应用程序中的一些 imports
更加清晰易懂。以下是其中列举的几个:
jsconfig.json
"paths": {
"@components/*": ["./src/components/*"],
"@constants/*": ["./src/constants/*"],
"@helpers/*": ["./src/helpers/*"]
}
当我构建生产环境时(客户端浏览器代码),我使用Webpack处理这些路径。我添加了一个resolve
属性,以便Webpack知道如何处理它们,并正确地打包它们。
webpack.config.js
resolve: {
alias: {
'@components': path.resolve(__dirname, 'src/components'),
'@constants': path.resolve(__dirname, 'src/constants'),
'@helpers': path.resolve(__dirname, 'src/helpers')
}
}
因此,Webpack知道如何解析和替换这些导入。但是Babel不知道。
当我将我的root/src
文件夹中的所有应用程序文件转译为functions/distApp
时,Babel保持这些导入不变。require('@components/something');
正如预期的那样,我的functions
代码不知道@components
解析到哪里。
问题
在Babel转译过程中如何访问这些imports
并更新它们?是否有插件可以做到这一点?我该如何处理这个问题?
附言:我想继续使用路径别名,因为深层文件导入浅层文件可能会变得很丑陋。例如:import helper from '../../../../../../../helpers/someHelper';
。而当我像这样导入时,如果我移动文件,导入就立即中断了,而import helper from '@helper/someHelper'
则完全不会中断。