首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >切换到在现有项目上创建React应用程序?

切换到在现有项目上创建React应用程序?
EN

Stack Overflow用户
提问于 2019-05-24 03:02:52
回答 3查看 10.8K关注 0票数 6

我有一个现有的应用程序,我正在使用"webpack-serve“,因为它是开发人员推荐给我的(当时他不打算再更新webpack-dev-server )。

不管怎样,现在它被弃用了,没有被使用,我回到了webpack- dev -server,但我在想,如果我只是通过努力,尝试使用类似“创建React应用程序”的东西,因为我真的不知道我是否可以使用这些我为webpack-serve制作的旧wepack.js文件,而且它们似乎也不是100%有效,因为每次我试图构建一个生产版本时,它都会给我一个开发版本。

webpack.common.js

代码语言:javascript
复制
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CleanWebpackPlugin = require("clean-webpack-plugin");
const webpack = require('webpack');

module.exports = {
  entry: ["@babel/polyfill", "./src/index.js"],
  output: {
    // filename and path are required
    filename: "main.js",
    path: path.resolve(__dirname, "dist"),
    publicPath: '/'
  },
  module: {
    rules: [
      {
        // JSX and JS are all .js
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
        }
      },
      {
        test: /\.(eot|svg|ttf|woff|woff2)$/,
        use: [
          {
            loader: 'file-loader',
            options: {}  
          }
        ]
      },
      {
        test: /\.(png|jpg|gif)$/,
        use: [
          {
            loader: 'file-loader',
            options: {}
          }
        ]
      }
    ]
  },
  plugins: [
    new CleanWebpackPlugin(["dist"]),
    new HtmlWebpackPlugin({
      template: "./src/index.html"
    }),
    new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
   })
  ]
};

webpack.dev

代码语言:javascript
复制
const path = require("path");
const merge = require("webpack-merge");
const convert = require("koa-connect");
const proxy = require("http-proxy-middleware");
const historyApiFallback = require("koa2-connect-history-api-fallback");

const common = require("./webpack.common.js");

module.exports = merge(common, {
  // Provides process.env.NODE_ENV with value development.
  // Enables NamedChunksPlugin and NamedModulesPlugin.
  mode: "development",
  devtool: "inline-source-map",
  // configure `webpack-serve` options here
  serve: {
    // The path, or array of paths, from which static content will be served.
    // Default: process.cwd()
    // see https://github.com/webpack-contrib/webpack-serve#options
    content: path.resolve(__dirname, "dist"),
    add: (app, middleware, options) => {
      // SPA are usually served through index.html so when the user refresh from another
      // location say /about, the server will fail to GET anything from /about. We use
      // HTML5 History API to change the requested location to the index we specified
      app.use(historyApiFallback());
      app.use(
        convert(
          // Although we are using HTML History API to redirect any sub-directory requests to index.html,
          // the server is still requesting resources like JavaScript in relative paths,
          // for example http://localhost:8080/users/main.js, therefore we need proxy to
          // redirect all non-html sub-directory requests back to base path too
          proxy(
            // if pathname matches RegEx and is GET
            (pathname, req) => pathname.match("/.*/") && req.method === "GET",
            {
              // options.target, required
              target: "http://localhost:8080",
              pathRewrite: {
                "^/.*/": "/" // rewrite back to base path
              }
            }
          )
        )
      );
    }
  },
  module: {
    rules: [
      {
        test: /\.(sa|sc|c)ss$/,
        use: ["style-loader", "css-loader", "sass-loader"]
      }
    ]
  }
});

webpack.prod

代码语言:javascript
复制
const merge = require("webpack-merge");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");
var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const common = require("./webpack.common.js");

module.exports = merge(common, {
  // Provides process.env.NODE_ENV with value production.
  // Enables FlagDependencyUsagePlugin, FlagIncludedChunksPlugin,
  // ModuleConcatenationPlugin, NoEmitOnErrorsPlugin, OccurrenceOrderPlugin,
  // SideEffectsFlagPlugin and UglifyJsPlugin.
  mode: "production",
  devtool: "source-map",
  // see https://webpack.js.org/configuration/optimization/
  optimization: {
    // minimize default is true
    minimizer: [
      // Optimize/minimize CSS assets.
      // Solves extract-text-webpack-plugin CSS duplication problem
      // By default it uses cssnano but a custom CSS processor can be specified
      new OptimizeCSSAssetsPlugin({})
    ]
  },
  module: {
    rules: [
      {
        test: /\.(sa|sc|c)ss$/,
        // only use MiniCssExtractPlugin in production and without style-loader
        use: [MiniCssExtractPlugin.loader, "css-loader", "sass-loader"]
      }
    ]
  },
  plugins: [
    // Mini CSS Extract plugin extracts CSS into separate files.
    // It creates a CSS file per JS file which contains CSS.
    // It supports On-Demand-Loading of CSS and SourceMaps.
    // It requires webpack 4 to work.
    new MiniCssExtractPlugin({
      filename: "[name].css",
      chunkFilename: "[id].css"
    }),
    new BundleAnalyzerPlugin()
  ]
});

编辑

如果我去哪里创建React App,我该如何处理这些东西?

我有一个带.babelrc的

代码语言:javascript
复制
  "presets": ["@babel/env", "@babel/react"],
  "plugins": [
    ["@babel/plugin-proposal-decorators", { "legacy": true }],
    "@babel/plugin-transform-object-assign",
    "@babel/plugin-proposal-object-rest-spread",
    "transform-class-properties",
    "emotion"
  ]

我认为react-app会处理一些东西,但不确定是否全部。我也有,如果你注意到在webpack.common中我正在轮询填充所有的东西,我是否只需要“react-app-polyfill”?

如何添加另一个"dev mode“?

代码语言:javascript
复制
  "scripts": {
    "dev": "cross-env NODE_ENV=dev webpack-serve --config webpack.dev.js --open",
    "prod": "cross-env NODE_ENV=prod  webpack -p --config webpack.prod.js",
    "qa": "cross-env NODE_ENV=QA webpack --config webpack.prod.js"
  },

我需要为QA设置Node_ENV,因为我需要检查指向在每个环境中更改的api。

EN

回答 3

Stack Overflow用户

发布于 2020-01-08 22:17:18

今天很简单,如下所示:

代码语言:javascript
复制
npx create-react-app .
票数 18
EN

Stack Overflow用户

发布于 2019-05-24 05:19:44

我已经做过几次这样的事情了。这就是我的方法:

  1. create-react-app my-app-cra //干净的slate
  2. npm i [list of dependencies] //去掉任何构建,编译,转译等在我的dependencies
  3. Copy文件夹上的possible
  4. npm start,保留了和src一样多的结构//并且祈祷吧!通常,在

中会涉及一些手动工作

要保存您的git历史记录:

  1. src复制到存储库外部的文件夹中
  2. 清理您的存储库git rm -rf
  3. 执行上述步骤(创建react应用程序、安装deps、将资源复制回in)
  4. git add //如果您保留文件夹结构,git将找到复制的文件(并注意到路径中可能的更改),并保留历史记录。
票数 4
EN

Stack Overflow用户

发布于 2019-05-24 03:38:39

create-react-appwebpack 4都是很好的选择,而且非常简单。在我看来,create-react-app是最实用的。

为了保存你的git历史,我建议:

  1. 创建一个分支并转到该分支。
  2. 安装并保存create-react-app的依赖关系和开发依赖关系。您将在您的package.json文件中看到它们。
  3. 执行配置。以创建-反应-应用程序存储库为例。

如果工作正常,请返回您的主分支并将此分支与migration.

  • Execute npm i合并,以便安装您从分支添加的依赖项。
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56281479

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档