简体   繁体   English

如何为使用 create-react-app 创建的 react 项目更新 webpack 配置?

[英]How to update webpack config for a react project created using create-react-app?

I have created a react project using create-react-app.我使用 create-react-app 创建了一个反应项目。 Now I need to update the webpack config, but I don't find the file anywhere.现在我需要更新 webpack 配置,但我在任何地方都找不到该文件。 Do I need to create this file myself or what is the process?我需要自己创建这个文件还是过程是什么? I am new to react and not really sure how to proceed from here.我是新来的反应,不确定如何从这里开始。

No need to run npm run eject无需运行npm run eject

Step 1步骤1

npm install react-app-rewired --save-dev

Step 2第2步

Add config-overrides.js to the project root directory.(NOT./src)config-overrides.js添加到项目根目录。(NOT./src)

// config-overrides.js
module.exports = function override(config, env) {
    // New config, e.g. config.plugins.push...
    return config
}

Step 3第 3 步

Restart your app.重新启动您的应用程序。 Done完毕

Option 1 - Eject your CRA选项 1 - 弹出您的 CRA

If you've just created your app using CRA, and haven't made big changes to it, you could use npm run eject - more about it here如果您刚刚使用 CRA 创建了您的应用程序,并且没有对其进行大的更改,您可以使用npm run eject - 更多信息请点击此处

Keep in mind that there is no going back (except by commits, of course) after doing this.请记住,执行此操作后没有回头路(当然,提交除外)。 This will basically provide you with webpack file and other files which are currently 'hidden' in CRA这基本上会为您提供 webpack 文件和其他目前在 CRA 中“隐藏”的文件

Some critiques and second thoughts about this method here这里方法的一些批评和重新思考

Option 2 - React App Rewired选项 2 - React App 重新布线

This might be the right choice for you.这可能是您的正确选择。 This allows you to extend your current webpack without ejecting, or messing up / making too many changes at your project as npm run eject will.这允许您扩展您当前的 webpack 而不会像npm run eject那样在项目中弹出或弄乱/进行太多更改。 Take a look at the package here此处查看 package

A great tutorial by Egghead.io using react-app-rewired here Egghead.io 在此处使用react-app-rewired rewired 的精彩教程

Webpack configuration is being handled by react-scripts . Webpack 配置由react-scripts处理。 I assume that you don't want to eject and just want to look at the config, you will find them in /node_modules/react-scripts/config我假设您不想弹出并且只想查看配置,您将在/node_modules/react-scripts/config中找到它们

webpack.config.dev.js. //used by `npm start`
webpack.config.prod.js //used by `npm run build`

I solved this problem by running a script between yarn install and yarn build.我通过在 yarn install 和 yarn build 之间运行脚本解决了这个问题。 After yarn install the webpack.config.json file is generated, then immediately run a script on Node that modifies it, and then run the build. yarn install webpack.config.json 文件生成后,立即在 Node 上运行修改它的脚本,然后运行构建。

My code:我的代码:
custom.webpack.config.js custom.webpack.config.js

const fs = require('fs')

// WebPack.config File
const fileConfig = 'node_modules/react-scripts/config/webpack.config.js'

new Promise((resolve) => {
   fs.readFile(fileConfig, 'utf8', function (err, data) {
      if (err) {
        return console.log(err)
      }
      resolve(data)
   })
}).then((file) => {
    
    let CodeAsString = "Code as String to save"

    let regexCode = /YourCodeRegex}/g

    let result = file.replace(regexCode, CodeAsString)

    fs.writeFile(fileConfig, result, function (err) {
        if (err) return console.log(err)
        console.log('The webpack.config file was modifed!')
    })
})

So, now do you need to edit the package.json to include this code in the process:那么,现在您是否需要编辑 package.json 以在过程中包含此代码:

"scripts": {
    "start": "node custom.webpack.config.js && react-scripts start",
    "build": "node custom.webpack.config.js && react-scripts build"
}

Done: :)完毕: :)

You can modify your webpack config or any other node_module using patch-package https://www.npmjs.com/package/patch-package您可以使用patch-package https://www.npmjs.com/package/patch-package修改您的 webpack 配置或任何其他 node_module

Install the version of react-scripts you want with npm i react-scripts@5.0.0使用npm i react-scripts@5.0.0安装您想要的react-scripts版本

Then go into node_modules/react-scripts/webpack/webpack.config.js .然后 go 进入node_modules/react-scripts/webpack/webpack.config.js Make the changes you need and then npx patch-package react-scripts进行所需的更改,然后npx patch-package react-scripts

patch-package will generate a file in your project root like patches/react-scripts+5.0.0.patch patch-package将在您的项目根目录中生成一个文件,例如patches/react-scripts+5.0.0.patch

Add post-install script to package.json with将安装后脚本添加到package.json

"scripts": {
    "postinstall": "patch-package",
    ...
}

Now whenever you run npm i you will automatically get this patch included with the installed library.现在,每当您运行npm i时,您将自动获得已安装库中包含的此补丁。

https://www.npmjs.com/package/react-app-rewired https://www.npmjs.com/package/react-app-rewired

Complete answer is:完整的答案是:

How to rewire your create-react-app project如何重新连接你的create-react-app项目

Create your app using create-react-app and then rewire it.使用create-react-app创建您的应用程序,然后重新连接它。

  1. Install react-app-rewired For create-react-app 2.x with Webpack 4:使用 Webpack 4 安装react-app-rewired对于create-react-app 2.x
 npm install react-app-rewired --save-dev

For create-react-app 1.x or react-scripts-ts with Webpack 3:对于使用 Webpack 3 create-react-app 1.xreact-scripts-ts

 npm install react-app-rewired@1.6.2 --save-dev
  1. Create a config-overrides.js file in the root directory在根目录下创建一个config-overrides.js文件
/* config-overrides.js */ module.exports = function override(config, env) { //do stuff with the webpack config... return config; }

like this:像这样:

+-- your-project
|   +-- config-overrides.js
|   +-- node_modules
|   +-- package.json
|   +-- public
|   +-- README.md
|   +-- src

for example:例如:

 module.exports = function override(config, env) { // New config, eg config.plugins.push... config.module.rules = [...config.module.rules, { test: /\.m?js/, resolve: { fullySpecified: false } } ] return config }
  1. 'Flip' the existing calls to react-scripts in npm scripts for start, build and test在 npm 脚本中“翻转”现有的对 react-scripts 的调用以进行启动、构建和测试

from:从:

/* package.json */ /* package.json */

 "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" }

To:至:

/* package.json */ /* package.json */

 "scripts": { "start": "react-app-rewired start", "build": "react-app-rewired build", "test": "react-app-rewired test", "eject": "react-scripts eject" }

Note: Do NOT flip the call for the eject script.注意:不要翻转弹出脚本的调用。 That gets run only once for a project, after which you are given full control over the webpack configuration making react-app-rewired no longer required.对于一个项目,它只运行一次,之后您可以完全控制 webpack 配置,从而不再需要 react-app-rewired。 There are no configuration options to rewire for the eject script.没有配置选项可以重新连接弹出脚本。

  1. Start the Dev Server启动开发服务器
npm start
  1. Build your app构建您的应用
npm run build

Here I found a simple solution without ejecting and we don't need to install other dependencies like react-app-rewired .在这里,我找到了一个简单的解决方案,无需弹出,我们不需要安装其他依赖项,例如react-app-rewired Because If you want to add some loaders or update some configurations we need to update the webpack config of create-react-app .因为如果你想添加一些加载器或更新一些配置,我们需要更新create-react-app的 webpack 配置。

How to do it?怎么做?

  1. Go to node_modules/react-scripts/config/webpack.config.js . Go 到node_modules/react-scripts/config/webpack.config.js
  2. Go to the line number 600 . Go 到the line number 600

Note: Here you'll see the following info注意:在这里您将看到以下信息

            // "file" loader makes sure those assets get served by WebpackDevServer.
            // When you `import` an asset, you get its (virtual) filename.
            // In production, they would get copied to the `build` folder.
            // This loader doesn't use a "test" so it will catch all modules
            // that fall through the other loaders.
            {
              loader: require.resolve('file-loader'),
              // Exclude `js` files to keep "css" loader working as it injects
              // its runtime that would otherwise be processed through "file" loader.
              // Also exclude `html` and `json` extensions so they get processed
              // by webpacks internal loaders.
              exclude: [/\.(js|mjs|jsx|ts|tsx)$/, /\.html$/, /\.json$/],
              options: {
                name: 'static/media/[name].[hash:8].[ext]',
              },
            },
            // ** STOP ** Are you adding a new loader?
            // Make sure to add the new loader(s) before the "file" loader.
  1. Add the following line to the above file-loader .将以下行添加到上面的file-loader
         // #1 Example customer loader for handling svg images 
            {
              test: /\.svg$/,
              use: ['@svgr/webpack']
            },

That's it而已

Warning: Be careful to change it and put your configuration at the appropriate place that's very important.警告:小心更改它并将您的配置放在非常重要的适当位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 create-react-app 项目中放置 webpack.config.js 的位置 - Where to place webpack.config.js in create-react-app project create-react-app webpack 配置和文件在哪里? - where is create-react-app webpack config and files? 如何从链接中删除“使用 create-react-app 创建”? - How to delete "created using create-react-app" from links? 如何编写在项目创建的 create-react-app 的单页反应路由器上工作的 JS - How to write JS which working on single page of react router at project created create-react-app 将 webpack 4 更新为 webpack 5 在现有的 create-react-app 上用 react-app-rewired 弹出 - Update webpack 4 to webpack 5 on an existing create-react-app ejected with react-app-rewired 如何使用特定版本的create-react-app创建react项目? - How to create a react project with specific version of create-react-app? 将React Webpack应用程序(不是使用create-react-app创建)部署到Github页面 - Deploying a React Webpack app (not created with create-react-app) to Github pages create-react-app 和 svgr 的 webpack 错误 - webpack errors with create-react-app & svgr 如何在 create-react-app 中使用 jest.config.js - How to use jest.config.js with create-react-app 使用create-react-app时如何在没有webpack依赖的情况下导入节点模块或JavaScript文件? - How to import node module or JavaScript file without webpack dependency when using create-react-app?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM