Docker部署前端应用时bundle.js加载报Unexpected token '<'错误排查
问题背景与故障现象
- 学习场景:跟随线上教程学习Docker,当前任务仅要求编写Dockerfile,初步判断问题出在Dockerfile编写环节,暂未梳理出高效的问题调试路径
- 核心故障:
- 基于构建完成的Docker镜像启动容器后,访问localhost可正常渲染index.html页面,但bundle.js无法正常加载,浏览器控制台抛出
Uncaught SyntaxError: Unexpected token '<'错误 - 本地环境直接执行webpack打包后,打开生成的index.html页面可正常渲染
- 基于构建完成的Docker镜像启动容器后,访问localhost可正常渲染index.html页面,但bundle.js无法正常加载,浏览器控制台抛出
- 排查进展:已移除Dockerfile中Node构建阶段原本的CMD行,将原单独执行的
RUN npm install指令调整为RUN npm install && npm start;当前已验证bundle.js文件可正常生成,且成功拷贝至nginx的静态资源目录,但原有报错仍未消除
项目相关配置文件
Dockerfile 配置
FROM node:8.15-alpine as build-stage COPY . /app RUN npm install && npm start FROM nginx:1.15 EXPOSE 80 COPY --from=build-stage /app /usr/share/nginx/html COPY --from=build-stage /app/nginx.conf /etc/nginx/conf.d/default.conf
入口页面 index.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Todo App</title> <link href="https://fonts.googleapis.com/css?family=Roboto+Slab" rel="stylesheet"> <link rel="stylesheet" href="./styles/main.css" > </head> <body> <div id="content"></div> <script src="./bundle.js"></script> </body> </html>
项目脚本与依赖配置 package.json
{ "name": "todos", "version": "1.0.0", "description": "This README would normally document whatever steps are necessary to get the application up and running.", "main": "index.js", "directories": { "test": "test" }, "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "webpack --mode=development" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "@babel/core": "^7.1.2", "@babel/preset-env": "^7.1.0", "@babel/preset-react": "^7.0.0", "babel-loader": "^8.2.2", "lodash": "^4.17.4", "react": "^16.2.0", "react-dom": "^16.2.0", "react-redux": "^5.0.6", "redux": "^3.7.2", "webpack": "^4.20.2", "webpack-cli": "^3.1.2" }, "devDependencies": {} }
Webpack 打包配置 webpack.config.js
const path = require('path'); module.exports = { context: __dirname, entry: './frontend/todo_redux.jsx', output: { path: path.resolve(__dirname), filename: 'bundle.js' }, module: { rules: [ { test: /\.jsx?$/, exclude: /(node_modules)/, use: { loader: 'babel-loader', options: { presets: ['@babel/env', '@babel/react'] } }, } ] }, devtool: 'source-map', resolve: { extensions: [".js", ".jsx", "*"] } };
Nginx 服务配置 nginx.conf
# 配置nginx服务用于渲染的静态资源路径 server { # 服务监听80端口 location / { # 静态资源根路径配置 root /usr/share/nginx/html; index index.html index.htm; try_files $uri $uri/ /index.html =404; } }
内容的提问来源于stack exchange,提问作者Samuel Samuelson
相关产品推荐
相关产品推荐

