切换到在现有项目上创建React App?

时间:2019-05-23 19:02:52

标签: reactjs webpack

开发人员向我建议,我有一个现有的应用程序正在使用“ webpack-serve”(当时他不再打算更新webpack-dev-server)。

无论如何,现在无论如何它都已被弃用并没有被使用,我回到了webpack-dev-server,但是我在考虑是否应该努力并尝试使用诸如“ Create React App”之类的东西,因为我没有这样做。我真的不知道我是否可以使用为webpack-serv制作的这些旧的wepack.js文件,而且每次我尝试构建生产版本时,它们似乎也无法100%正常工作。

webpack.common.js

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

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

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与

  "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.com中注意到了我,则我也正在轮询所有内容,我是否只需要“ react-app-polyfill”?

如何添加另一个“开发模式”

  "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"
  },

我需要设置Node_ENV进行质量检查,因为我要检查一下指向在每个环境中都发生变化的api。

3 个答案:

答案 0 :(得分:8)

今天很简单,如下所示:

npx create-react-app .

答案 1 :(得分:0)

create-react-appwebpack 4都是不错的选择,而且非常简单。我认为,create-react-app是最实用的。

为了保存您的git历史记录,我建议:

  1. 创建一个分支并转到它。
  2. 安装并保存create-react-app的依赖关系和开发依赖关系。您会在package.json文件中看到它们。
  3. 进行配置。以create-react-app存储库为例。
  4. 如果一切正常,请返回您的master分支并将该分支与迁移合并。
  5. 执行npm i以便安装从分支添加的依赖项。

答案 2 :(得分:0)

我不得不做几次这样的事情。这是我的方法:

  1. from io import BytesIO import zlib from zipfile import ZipFile # starting from something similar to this: the_byte_string = b"x\x9cL{S`x\xd2m\x9c\x16\xdb\xb6m\xa7c\....." b = BytesIO(zlib.decompress(the_byte_string)) z = ZipFile(b) # extracts all the files in your .zip folder for you. z.extractall() //清理板岩
  2. create-react-app my-app-cra //减去任何构建,编译,转译等依赖项
  3. 复制我的npm i [list of dependencies]文件夹,并保留尽可能多的结构
  4. src //保持手指交叉!通常,需要一些手工工作

要保留您的git历史记录:

  1. 将您的npm start复制到存储库之外的文件夹中
  2. 清理您的仓库src
  3. 执行上述步骤(创建React应用,安装deps,复制src到其中)
  4. git rm -rf //如果您保留文件夹结构,则git会找到复制过来的文件(并会注意到路径可能发生变化)并优雅地处理,并保留历史记录。