未eject的Create React App项目Babel转译时Docker构建失败求助
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"transpile": "NODE_ENV=production babel src --out-dir transpiled --presets env,react-app",
"start:prod": "NODE_ENV=production node server.js"
},
...
--- # Answer Let's break down the possible issues and fix them step by step: ## 1. Missing Babel Dependencies create-react-app wraps `babel-preset-react-app` as an internal dependency, so if you haven't explicitly installed the required Babel packages, your transpile command will fail. First, make sure you have all necessary dev dependencies installed: Add this step to your Dockerfile (or run it locally and commit the changes): ```bash npm install --save-dev @babel/cli babel-preset-env babel-preset-react-app
2. Fix the Transpile Command Syntax
The preset names in your command might be incorrect (modern versions use scoped packages like @babel/preset-react-app), and passing presets via the command line can be error-prone. Instead, create a .babelrc configuration file in your project root to manage presets:
{ "presets": [ "babel-preset-env", "babel-preset-react-app" ] }
Then update your transpile script in package.json to remove the presets argument—Babel will automatically use the .babelrc config:
"transpile": "NODE_ENV=production babel src --out-dir transpiled"
3. Optimize Dockerfile for Reliability
Your current Dockerfile can be improved to leverage Docker's cache and ensure consistent environments:
# Use a specific Node version (alpine is lighter) to avoid compatibility issues FROM node:18-alpine # Set a working directory to keep files organized WORKDIR /app # Copy package files first to cache dependency installs COPY package*.json ./ # Install all dependencies (including dev deps, since transpile needs Babel) RUN npm install # Copy the rest of your project files COPY . . # Run build and transpile steps RUN npm run build RUN npm run transpile # Set production environment explicitly ENV NODE_ENV=production # Expose the port your app uses EXPOSE $PORT # Start the production server CMD ["npm", "run", "start:prod"]
4. Check if Ejecting is Necessary
If you haven't ejected your create-react-app project, some Babel configurations are hidden in react-scripts. If the above fixes don't work, you might need to run npm run eject (note: this is irreversible) to gain full control over the Babel setup, then adjust the ejected config files to match your transpile needs.
内容的提问来源于stack exchange,提问作者Hsaido

