Skip to content
This repository has been archived by the owner on Nov 28, 2024. It is now read-only.

Commit

Permalink
feat: upgrade babel & webpack config
Browse files Browse the repository at this point in the history
  • Loading branch information
zerosoul committed Dec 8, 2020
1 parent 5b24fa0 commit 80cc0a7
Show file tree
Hide file tree
Showing 13 changed files with 2,175 additions and 2,607 deletions.
22 changes: 0 additions & 22 deletions .babelrc

This file was deleted.

28 changes: 28 additions & 0 deletions babel.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
const presets = [
[
'@babel/preset-env',
{
modules: false,
useBuiltIns: 'usage',
corejs: 3,
targets: {
chrome: 70
}
}
],
[
'@babel/preset-react',
{
runtime: 'automatic'
}
]
];
const plugins = [
process.env.NODE_ENV == 'development' && 'react-refresh/babel',
'@babel/plugin-syntax-dynamic-import',
'@babel/plugin-proposal-class-properties',
'@babel/plugin-proposal-json-strings',
'@babel/plugin-proposal-nullish-coalescing-operator'
].filter(Boolean);

module.exports = { presets, plugins };
21 changes: 15 additions & 6 deletions config/env.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
'use strict';

const fs = require('fs');
const path = require('path');
const paths = require('./paths');
Expand All @@ -7,18 +9,20 @@ delete require.cache[require.resolve('./paths')];

const NODE_ENV = process.env.NODE_ENV;
if (!NODE_ENV) {
throw new Error('The NODE_ENV environment variable is required but was not specified.');
throw new Error(
'The NODE_ENV environment variable is required but was not specified.'
);
}

// https://github.com/bkeepers/dotenv#what-other-env-files-can-i-use
const dotenvFiles = [
`${paths.dotenv}.${NODE_ENV}.local`,
`${paths.dotenv}.${NODE_ENV}`,
// Don't include `.env.local` for `test` environment
// since normally you expect tests to produce the same
// results for everyone
NODE_ENV !== 'test' && `${paths.dotenv}.local`,
paths.dotenv
`${paths.dotenv}.${NODE_ENV}`,
paths.dotenv,
].filter(Boolean);

// Load environment variables from .env* files. Suppress warnings using silent
Expand All @@ -30,7 +34,7 @@ dotenvFiles.forEach(dotenvFile => {
if (fs.existsSync(dotenvFile)) {
require('dotenv-expand')(
require('dotenv').config({
path: dotenvFile
path: dotenvFile,
})
);
}
Expand Down Expand Up @@ -80,15 +84,20 @@ function getClientEnvironment(publicUrl) {
// and `sockPort` options in webpack-dev-server.
WDS_SOCKET_HOST: process.env.WDS_SOCKET_HOST,
WDS_SOCKET_PATH: process.env.WDS_SOCKET_PATH,
WDS_SOCKET_PORT: process.env.WDS_SOCKET_PORT
WDS_SOCKET_PORT: process.env.WDS_SOCKET_PORT,
// Whether or not react-refresh is enabled.
// react-refresh is not 100% stable at this time,
// which is why it's disabled by default.
// It is defined here so it is available in the webpackHotDevClient.
FAST_REFRESH: process.env.FAST_REFRESH !== 'false',
}
);
// Stringify all values so we can feed into webpack DefinePlugin
const stringified = {
'process.env': Object.keys(raw).reduce((env, key) => {
env[key] = JSON.stringify(raw[key]);
return env;
}, {})
}, {}),
};

return { raw, stringified };
Expand Down
20 changes: 14 additions & 6 deletions config/getHttpsConfig.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
'use strict';

const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
Expand All @@ -12,24 +14,30 @@ function validateKeyAndCerts({ cert, key, keyFile, crtFile }) {
// publicEncrypt will throw an error with an invalid cert
encrypted = crypto.publicEncrypt(cert, Buffer.from('test'));
} catch (err) {
throw new Error(`The certificate "${chalk.yellow(crtFile)}" is invalid.\n${err.message}`);
throw new Error(
`The certificate "${chalk.yellow(crtFile)}" is invalid.\n${err.message}`
);
}

try {
// privateDecrypt will throw an error with an invalid key
crypto.privateDecrypt(key, encrypted);
} catch (err) {
throw new Error(`The certificate key "${chalk.yellow(keyFile)}" is invalid.\n${err.message}`);
throw new Error(
`The certificate key "${chalk.yellow(keyFile)}" is invalid.\n${
err.message
}`
);
}
}

// Read file and throw an error if it doesn't exist
function readEnvFile(file, type) {
if (!fs.existsSync(file)) {
throw new Error(
`You specified ${chalk.cyan(type)} in your env, but the file "${chalk.yellow(
file
)}" can't be found.`
`You specified ${chalk.cyan(
type
)} in your env, but the file "${chalk.yellow(file)}" can't be found.`
);
}
return fs.readFileSync(file);
Expand All @@ -46,7 +54,7 @@ function getHttpsConfig() {
const keyFile = path.resolve(paths.appPath, SSL_KEY_FILE);
const config = {
cert: readEnvFile(crtFile, 'SSL_CRT_FILE'),
key: readEnvFile(keyFile, 'SSL_KEY_FILE')
key: readEnvFile(keyFile, 'SSL_KEY_FILE'),
};

validateKeyAndCerts({ ...config, keyFile, crtFile });
Expand Down
58 changes: 36 additions & 22 deletions config/modules.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
const fs = require('fs');
const path = require('path');
const paths = require('./paths');
const chalk = require('react-dev-utils/chalk');
"use strict";

const fs = require("fs");
const path = require("path");
const paths = require("./paths");
const chalk = require("react-dev-utils/chalk");
const resolve = require("resolve");

/**
* Get additional module paths based on the baseUrl of a compilerOptions object.
Expand All @@ -11,27 +14,20 @@ const chalk = require('react-dev-utils/chalk');
function getAdditionalModulePaths(options = {}) {
const baseUrl = options.baseUrl;

// We need to explicitly check for null and undefined (and not a falsy value) because
// TypeScript treats an empty string as `.`.
if (baseUrl == null) {
// If there's no baseUrl set we respect NODE_PATH
// Note that NODE_PATH is deprecated and will be removed
// in the next major release of create-react-app.

const nodePath = process.env.NODE_PATH || '';
return nodePath.split(path.delimiter).filter(Boolean);
if (!baseUrl) {
return "";
}

const baseUrlResolved = path.resolve(paths.appPath, baseUrl);

// We don't need to do anything if `baseUrl` is set to `node_modules`. This is
// the default behavior.
if (path.relative(paths.appNodeModules, baseUrlResolved) === '') {
if (path.relative(paths.appNodeModules, baseUrlResolved) === "") {
return null;
}

// Allow the user set the `baseUrl` to `appSrc`.
if (path.relative(paths.appSrc, baseUrlResolved) === '') {
if (path.relative(paths.appSrc, baseUrlResolved) === "") {
return [paths.appSrc];
}

Expand All @@ -40,15 +36,15 @@ function getAdditionalModulePaths(options = {}) {
// not transpiled outside of `src`. We do allow importing them with the
// absolute path (e.g. `src/Components/Button.js`) but we set that up with
// an alias.
if (path.relative(paths.appPath, baseUrlResolved) === '') {
if (path.relative(paths.appPath, baseUrlResolved) === "") {
return null;
}

// Otherwise, throw an error.
throw new Error(
chalk.red.bold(
"Your project's `baseUrl` can only be set to `src` or `node_modules`." +
' Create React App does not support other values at this time.'
" Create React App does not support other values at this time."
)
);
}
Expand All @@ -67,20 +63,37 @@ function getWebpackAliases(options = {}) {

const baseUrlResolved = path.resolve(paths.appPath, baseUrl);

if (path.relative(paths.appPath, baseUrlResolved) === '') {
if (path.relative(paths.appPath, baseUrlResolved) === "") {
return {
src: paths.appSrc
src: paths.appSrc,
};
}
}

function getModules() {
// Check if jsconfig.json
// Check if TypeScript is setup
const hasTsConfig = fs.existsSync(paths.appTsConfig);
const hasJsConfig = fs.existsSync(paths.appJsConfig);

if (hasTsConfig && hasJsConfig) {
throw new Error(
"You have both a tsconfig.json and a jsconfig.json. If you are using TypeScript please remove your jsconfig.json file."
);
}

let config;

if (hasJsConfig) {
// If there's a tsconfig.json we assume it's a
// TypeScript project and set up the config
// based on tsconfig.json
if (hasTsConfig) {
const ts = require(resolve.sync("typescript", {
basedir: paths.appNodeModules,
}));
config = ts.readConfigFile(paths.appTsConfig, ts.sys.readFile).config;
// Otherwise we'll check if there is jsconfig.json
// for non TS projects.
} else if (hasJsConfig) {
config = require(paths.appJsConfig);
}

Expand All @@ -91,7 +104,8 @@ function getModules() {

return {
additionalModulePaths: additionalModulePaths,
webpackAliases: getWebpackAliases(options)
webpackAliases: getWebpackAliases(options),
hasTsConfig,
};
}

Expand Down
66 changes: 33 additions & 33 deletions config/paths.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
const path = require('path');
const fs = require('fs');
const getPublicUrlOrPath = require('react-dev-utils/getPublicUrlOrPath');
const path = require("path");
const fs = require("fs");
const getPublicUrlOrPath = require("react-dev-utils/getPublicUrlOrPath");

// 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 resolveApp = (relativePath) => path.resolve(appDirectory, relativePath);

// We use `PUBLIC_URL` environment variable or "homepage" field to infer
// "public path" at which the app is served.
Expand All @@ -14,28 +14,28 @@ const resolveApp = relativePath => path.resolve(appDirectory, relativePath);
// 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.
const publicUrlOrPath = getPublicUrlOrPath(
process.env.NODE_ENV === 'development',
require(resolveApp('package.json')).homepage,
process.env.NODE_ENV === "development",
require(resolveApp("package.json")).homepage,
process.env.PUBLIC_URL
);

const moduleFileExtensions = [
'web.mjs',
'mjs',
'web.js',
'js',
'web.ts',
'ts',
'web.tsx',
'tsx',
'json',
'web.jsx',
'jsx'
"web.mjs",
"mjs",
"web.js",
"js",
"web.ts",
"ts",
"web.tsx",
"tsx",
"json",
"web.jsx",
"jsx",
];

// Resolve file paths in the same order as webpack
const resolveModule = (resolveFn, filePath) => {
const extension = moduleFileExtensions.find(extension =>
const extension = moduleFileExtensions.find((extension) =>
fs.existsSync(resolveFn(`${filePath}.${extension}`))
);

Expand All @@ -48,21 +48,21 @@ const resolveModule = (resolveFn, filePath) => {

// config after eject: we're in ./config/
module.exports = {
dotenv: resolveApp('.env'),
appPath: resolveApp('.'),
appBuild: resolveApp('build'),
appPublic: resolveApp('public'),
appHtml: resolveApp('public/index.html'),
appIndexJs: resolveModule(resolveApp, 'src/index'),
appPackageJson: resolveApp('package.json'),
appSrc: resolveApp('src'),
appTsConfig: resolveApp('tsconfig.json'),
appJsConfig: resolveApp('jsconfig.json'),
yarnLockFile: resolveApp('yarn.lock'),
testsSetup: resolveModule(resolveApp, 'src/setupTests'),
proxySetup: resolveApp('src/setupProxy.js'),
appNodeModules: resolveApp('node_modules'),
publicUrlOrPath
dotenv: resolveApp(".env"),
appPath: resolveApp("."),
appBuild: resolveApp("build"),
appPublic: resolveApp("public"),
appHtml: resolveApp("public/index.html"),
appIndexJs: resolveModule(resolveApp, "src/index"),
appPackageJson: resolveApp("package.json"),
appSrc: resolveApp("src"),
appTsConfig: resolveApp("tsconfig.json"),
appJsConfig: resolveApp("jsconfig.json"),
yarnLockFile: resolveApp("yarn.lock"),
proxySetup: resolveApp("src/setupProxy.js"),
appNodeModules: resolveApp("node_modules"),
swSrc: resolveModule(resolveApp, "src/service-worker"),
publicUrlOrPath,
};

module.exports.moduleFileExtensions = moduleFileExtensions;
Loading

0 comments on commit 80cc0a7

Please sign in to comment.