create-react-app默认webpack配置解析及自定义

这边文章逻辑较乱,如果你有看过eject的create-react-app相关webpack源码,阅读下面的文章说不定会有意外收获

1. dotenv

Dotenv是一个零依赖模块,可以将.env文件中的环境变量加载process.env

2. 修改配置项,如端口号

//Windows (cmd.exe)
set PORT=true&&npm start

//Windows (Powershell)
($env:PORT = "true") -and (npm start)

//Linux, macOS (Bash)
PORT=true npm start

3. react-dev-utils

此程序包包含Create React App使用的一些实用程序。主要用于webpack;

//可以在GitHub参照源代码
clearConsole(); //清空控制台信息
openBrowser(url); //在控制台打开网址

4. path模块相关介绍

// 返回绝对路径(fs.realpathSync)
const appDirectory = fs.realpathSync(process.cwd());
path.isAbsolute() 方法检测path是否为绝对路径

path.delimiter 系统分隔符
  delete require.cache[require.resolve('./paths')];//清除缓存

5. config/paths.js

'use strict';

const path = require('path');
const fs = require('fs');
const url = require('url');

// Make sure any symlinks in the project folder are resolved:
// https://github.com/facebook/create-react-app/issues/637
const appDirectory = fs.realpathSync(process.cwd());
const resolveApp = relativePath => path.resolve(appDirectory, relativePath);

const envPublicUrl = process.env.PUBLIC_URL;

// 路径是否添加'/'后缀
function ensureSlash(inputPath, needsSlash) { const hasSlash = inputPath.endsWith('/'); if (hasSlash && !needsSlash) { return inputPath.substr(0, inputPath.length - 1); } else if (!hasSlash && needsSlash) { return `${inputPath}/`; } else { return inputPath; } } const getPublicUrl = appPackageJson => envPublicUrl || require(appPackageJson).homepage; //通过require加载json文件,然后读取里面的配置 // We use `PUBLIC_URL` environment variable or "homepage" field to infer // "public path" at which the app is served. // Webpack needs to know it to put the right

你可能感兴趣的:(create-react-app默认webpack配置解析及自定义)