使用Shopify CLI创建的React应用无法在本地(Heroku)运行
在Heroku上运行Shopify CLI创建的应用(无需eject)
问题背景
用Shopify CLI创建的应用依赖shopify app dev启动,但Heroku无法执行该CLI命令,尝试直接运行JSX文件或适配react-scripts均遇到目录/文件结构不兼容问题,且不想eject应用。
方案1:调整目录结构适配react-scripts
react-scripts默认要求src(存放源码)和public(存放静态资源)目录,按以下步骤调整:
- 在
web目录下新建src文件夹,将原frontend中的入口文件(如index.js/App.jsx)移到web/src下 - 将原
frontend中的静态文件(如index.html)移到web/public目录 - 修改
web/package.json的scripts:"scripts": { "start": "react-scripts start", "build": "react-scripts build" } - 在Heroku的环境变量中配置Shopify所需的变量:
SHOPIFY_API_KEY、SHOPIFY_API_SECRET、SCOPES、HOST等
方案2:自定义Babel+Webpack配置(不依赖react-scripts)
如果不想改动原有目录结构,可自行配置构建工具:
- 安装依赖(在
web目录下执行):npm install @babel/core @babel/preset-env @babel/preset-react babel-loader webpack webpack-cli webpack-dev-server html-webpack-plugin style-loader css-loader --save-dev - 在
web目录下创建babel.config.json:{ "presets": [ "@babel/preset-env", "@babel/preset-react" ] } - 创建
webpack.config.js:const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: './frontend/App.jsx', // 替换为你的实际入口文件路径 output: { path: path.resolve(__dirname, 'dist'), filename: 'bundle.[contenthash].js' }, module: { rules: [ { test: /\.(js|jsx)$/, exclude: /node_modules/, use: 'babel-loader' }, { test: /\.css$/, use: ['style-loader', 'css-loader'] } ] }, resolve: { extensions: ['.js', '.jsx'] }, plugins: [ new HtmlWebpackPlugin({ template: './frontend/index.html' // 替换为你的实际HTML模板路径 }) ], devServer: { port: 3000, hot: true, historyApiFallback: true } }; - 修改
web/package.json的scripts:"scripts": { "start": "webpack-dev-server --mode development", "build": "webpack --mode production" } - 若要在Heroku上运行生产环境,需添加一个简单的Express服务器:
- 安装
express:npm install express --save - 在
web目录下创建server.js:const express = require('express'); const path = require('path'); const app = express(); app.use(express.static(path.join(__dirname, 'dist'))); app.get('*', (req, res) => { res.sendFile(path.join(__dirname, 'dist', 'index.html')); }); const PORT = process.env.PORT || 3000; app.listen(PORT, () => console.log(`Server running on port ${PORT}`)); - 更新scripts:
"scripts": { "start": "node server.js", "build": "webpack --mode production", "heroku-postbuild": "npm run build" }
- 安装
方案3:使用Shopify CLI的构建命令
利用Shopify CLI自带的构建能力生成生产包:
- 在项目根目录的
package.json中添加Heroku构建脚本:"scripts": { "heroku-postbuild": "shopify app build" } - 配置Heroku启动命令,用于serve构建后的静态文件(可参考方案2中的
server.js) - 在Heroku环境变量中配置所有Shopify所需的变量
内容的提问来源于stack exchange,提问作者Jacob
相关产品推荐
相关产品推荐

