我知道自己喜欢你。但我不知道将来在哪里。因为我知道,无论哪里,你都不会带我去。而记忆打亮你的微笑,要如此用力才变得欢喜。 -----<从你的全世界路过>
说正事的分割线
代码分析
'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/facebookincubator/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(path, needsSlash) {
const hasSlash = path.endsWith('/');
if (hasSlash && !needsSlash) {
return path.substr(path, path.length - 1);
} else if (!hasSlash && needsSlash) {
return `${path}/`;
} else {
return path;
}
}
//格式化路径.是否末尾带/
const getPublicUrl = appPackageJson =>
envPublicUrl || require(appPackageJson).homepage;
// 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 <script> hrefs into HTML even in
// single-page apps that may serve index.html for nested URLs like /todos/42.
// We can't use a relative path in HTML because we don't want to load something
// like /todos/42/static/js/bundle.7289d.js. We have to know the root.
function getServedPath(appPackageJson) {
const publicUrl = getPublicUrl(appPackageJson);
const servedUrl =
envPublicUrl || (publicUrl ? url.parse(publicUrl).pathname : '/');
return ensureSlash(servedUrl, true);
}
//上面这两个函数主要就是 返回packjson中的homepage属性 如果没有process.env 又没有homepage属性 就返回 根路径 这非常的重要
// config after eject: we're in ./config/
module.exports = {
dotenv: resolveApp('.env'),
appBuild: resolveApp('build'),
appPublic: resolveApp('public'),
appHtml: resolveApp('public/index.html'),
appIndexJs: resolveApp('src/index.js'),
appPackageJson: resolveApp('package.json'),
appSrc: resolveApp('src'),
yarnLockFile: resolveApp('yarn.lock'),
testsSetup: resolveApp('src/setupTests.js'),
appNodeModules: resolveApp('node_modules'),
publicUrl: getPublicUrl(resolveApp('package.json')),
servedPath: getServedPath(resolveApp('package.json')),
};
代码太短 没啥好讲的 主要就是提供给项目的各种路径 .包括构建路径 public路径等等
我们打印一下相关的路径会发现其中的包含的信息很多很多 ....
利用path.js修改项目的运行路径
情景 如果你的项目运行的目录并不是根目录下 例如是xxx.com/html/
那么我们可以根据上面的分析 在package.json中添加homepage的属性 .来使buld时各种静态资源的正确引入.
打印一下和build一下结果看一下
publicUrl 和serverdPath 均修改为 /html/
build之后也可以发现 均自动引入了正确路径
path.js实在没啥好讲,代码注释一下,讲一下功能,一共也没几个字,所以本章比较水.....下面一章 就要开始大头了.. 主要配置文件的讲解.