React
cra webpack 냅다 주석 해보기
Jinsi | Tech
2022. 8. 21. 00:36
어우 방대하구나 방대해!
'use strict';
const fs = require('fs');
const path = require('path');
const webpack = require('webpack');
const resolve = require('resolve');
const HtmlWebpackPlugin = require('html-webpack-plugin'); // html 파일을 템플릿으로 생성할 수 있게 도와주는 플러그인
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin'); //대소문자를 다르게 처리하는 파일 시스템에서도 모두 동일하게 동작시키게 하기 위해 웹팩 실행 시 file path의 대소문자가 정확히 일치하는지 체크.
const InlineChunkHtmlPlugin = require('react-dev-utils/InlineChunkHtmlPlugin');
const TerserPlugin = require('terser-webpack-plugin'); //자바스크립트 코드를 난독화하고 debugger 구문을 제거
const MiniCssExtractPlugin = require('mini-css-extract-plugin'); //css 파일을 별도 파일로 추출하 - 최적화
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin'); //CSS를 최적화하고 축소
const { WebpackManifestPlugin } = require('webpack-manifest-plugin'); //최적화 https://trend21c.tistory.com/2175
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin'); //%PUBLIC_URL% 사용 가능
const WorkboxWebpackPlugin = require('workbox-webpack-plugin');
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin'); //creact-app에서 분기된 플러그인 node_modules/ 디렉토리 외부에서 가져오는 것 방지
const getCSSModuleLocalIdent = require('react-dev-utils/getCSSModuleLocalIdent'); // CSS Module을 위한 플러그인
const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin');
// const ESLintPlugin = require('eslint-webpack-plugin'); //Eslint 설정
const paths = require('./paths');
const modules = require('./modules');
const getClientEnvironment = require('./env');
const ModuleNotFoundPlugin = require('react-dev-utils/ModuleNotFoundPlugin');
//타입스크립트 빌드할때 성능을 향상 시키는 플러그인
const ForkTsCheckerWebpackPlugin =
process.env.TSC_COMPILE_ON_ERROR === 'true'
? require('react-dev-utils/ForkTsCheckerWarningWebpackPlugin')
: require('react-dev-utils/ForkTsCheckerWebpackPlugin');
const createEnvironmentHash = require('./webpack/persistentCache/createEnvironmentHash');
// Source maps are resource heavy and can cause out of memory issue for large source files.
const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== 'false';
const reactRefreshRuntimeEntry = require.resolve('react-refresh/runtime'); //Fast Refresh Module
const reactRefreshWebpackPluginRuntimeEntry = require.resolve(
'@pmmmwh/react-refresh-webpack-plugin',
); // Fast Refresh Module (TIP : require.resolve - 필요한 파일만 가져옴 , require - 모듈자체를 가져옴)
const babelRuntimeEntry = require.resolve('babel-preset-react-app');
const babelRuntimeEntryHelpers = require.resolve(
'@babel/runtime/helpers/esm/assertThisInitialized',
{ paths: [babelRuntimeEntry] },
);
const babelRuntimeRegenerator = require.resolve('@babel/runtime/regenerator', {
paths: [babelRuntimeEntry],
});
// Some apps do not need the benefits of saving a web request, so not inlining the chunk
// makes for a smoother build process.
const shouldInlineRuntimeChunk = process.env.INLINE_RUNTIME_CHUNK !== 'false';
const emitErrorsAsWarnings = process.env.ESLINT_NO_DEV_ERRORS === 'true';
// const disableESLintPlugin = process.env.DISABLE_ESLINT_PLUGIN === 'true';
const imageInlineSizeLimit = parseInt(
process.env.IMAGE_INLINE_SIZE_LIMIT || '10000',
);
// Check if TypeScript is setup
const useTypeScript = fs.existsSync(paths.appTsConfig);
// Check if Tailwind config exists
const useTailwind = fs.existsSync(
path.join(paths.appPath, 'tailwind.config.js'),
);
// Get the path to the uncompiled service worker (if it exists).
const swSrc = paths.swSrc;
// style files regexes
const cssRegex = /\.css$/;
const cssModuleRegex = /\.module\.css$/;
const sassRegex = /\.(scss|sass)$/;
const sassModuleRegex = /\.module\.(scss|sass)$/;
const hasJsxRuntime = (() => {
if (process.env.DISABLE_NEW_JSX_TRANSFORM === 'true') {
return false;
}
try {
require.resolve('react/jsx-runtime');
return true;
} catch (e) {
return false;
}
})();
// 상용 및 dev 설정
// 개발자의 경험 ,신속한 재구축, 최소한의 번들에 초점
module.exports = function (webpackEnv) {
const isEnvDevelopment = webpackEnv === 'development';
const isEnvProduction = webpackEnv === 'production';
// 프로덕션에서 프로파일링을 활성화하기 위해 사용되는 변수
// alias 오브젝트로 전달되었습니다. build 명령에 전달된 경우 플래그를 사용합니다.
const isEnvProductionProfile =
isEnvProduction && process.argv.includes('--profile');
// 앱에 'path.publicUrlOrPath'를 제공합니다.
// index.html' 및 process.env에서 %PUBLIC_URL%로 표시됩니다.자바스크립트의 PUBLIC_URL.
// %PUBLIC_URL%/xyz가 %PUBLIC_URL%xyz보다 좋아 보이므로 후행 슬래시를 생략합니다.
// 앱에 삽입할 환경 변수를 가져옵니다.
const env = getClientEnvironment(paths.publicUrlOrPath.slice(0, -1));
const shouldUseReactRefresh = env.raw.FAST_REFRESH;
console.log(shouldUseReactRefresh);
// 스타일 로더를 가져오는 공통 함수
const getStyleLoaders = (cssOptions, preProcessor) => {
const loaders = [
isEnvDevelopment && require.resolve('style-loader'),
isEnvProduction && {
loader: MiniCssExtractPlugin.loader,
// css는 "static/css"에 있습니다. "../../"를 사용하여 index.darges 폴더를 찾습니다.
// 운영 'paths.publicUrlOrPath'는 상대 경로일 수 있습니다.
options: paths.publicUrlOrPath.startsWith('.')
? { publicPath: '../../' }
: {},
},
{
loader: require.resolve('css-loader'),
options: cssOptions,
},
{
// PostCSS용 옵션입니다.이러한 옵션은 다음과 같습니다.
// 에서 지정한 브라우저 지원에 따라 벤더 프리픽스를 추가합니다.
// package.json
loader: require.resolve('postcss-loader'),
options: {
postcssOptions: {
// 외부 CSS Import를 동작시키기 위해 필요
// https://github.com/facebook/create-react-app/issues/2677
ident: 'postcss',
config: false,
plugins: !useTailwind
? [
'postcss-flexbugs-fixes',
[
'postcss-preset-env',
{
autoprefixer: {
flexbox: 'no-2009',
},
stage: 3,
},
],
// PostCSS Normalize를 디폴트옵션으로 리셋 cSS로 추가합니다.
// 패키지의 브라우저 목록 구성을 따르도록 합니다.json
// 이를 통해 사용자는 필요에 따라 타깃 동작을 맞춤화할 수 있습니다.
'postcss-normalize',
]
: [
'tailwindcss',
'postcss-flexbugs-fixes',
[
'postcss-preset-env',
{
autoprefixer: {
flexbox: 'no-2009',
},
stage: 3,
},
],
],
},
sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment,
},
},
].filter(Boolean);
if (preProcessor) {
loaders.push(
{
loader: require.resolve('resolve-url-loader'),
options: {
sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment,
root: paths.appSrc,
},
},
{
loader: require.resolve(preProcessor),
options: {
sourceMap: true,
},
},
);
}
return loaders;
};
return {
target: ['browserslist'],
mode: isEnvProduction ? 'production' : isEnvDevelopment && 'development',
// Stop compilation early in production
bail: isEnvProduction,
devtool: isEnvProduction
? shouldUseSourceMap
? 'source-map'
: false
: // : isEnvDevelopment && "cheap-module-source-map",
isEnvDevelopment && 'cheap-module-source-map',
// 이것들이 우리 지원서의 "진입점"입니다.
// 즉, JS 번들에 포함된 "root" Import가 됩니다.
// entry: path.resolve(__dirname, './src/js/index'),
entry: paths.appIndexJs,
devServer: {
hot: true,
},
output: {
//빌드 폴더
path: paths.appBuild,
// 출력에서 생성된 require()에 /* filename */ 주석을 추가합니다.
pathinfo: isEnvDevelopment,
// 메인 번들이 1개, 비동기 청크당 파일이 1개씩 있습니다.
// 개발에서는 실제 파일을 생성하지 않습니다.
filename: isEnvProduction
? 'static/js/[name].[contenthash:8].js'
: isEnvDevelopment && 'static/js/bundle.min.js',
// 코드 분할을 사용하는 경우 추가 JS 청크 파일도 있습니다.
chunkFilename: isEnvProduction
? 'static/js/[name].[contenthash:8].chunk.js'
: isEnvDevelopment && 'static/js/[name].chunk.js',
assetModuleFilename: 'static/media/[name].[hash][ext]',
// webpack은 'public Path'를 사용하여 앱이 어디서 제공되는지 결정합니다.
// 후행 슬래시가 필요합니다.그렇지 않으면 파일자산에 잘못된 경로가 생깁니다.
// 홈페이지에서 "public path"(/ 또는 /my-project 등)를 추론했습니다.
publicPath: paths.publicUrlOrPath,
// 소스 맵 항목을 원래 디스크 위치로 지정(Windows에서는 URL 형식으로 포맷)
devtoolModuleFilenameTemplate: isEnvProduction
? info =>
path
.relative(paths.appSrc, info.absoluteResourcePath)
.replace(/\\/g, '/')
: isEnvDevelopment &&
(info => path.resolve(info.absoluteResourcePath).replace(/\\/g, '/')),
},
cache: {
type: 'filesystem',
version: createEnvironmentHash(env.raw),
cacheDirectory: paths.appWebpackCache,
store: 'pack',
buildDependencies: {
defaultWebpack: ['webpack/lib/'],
config: [__filename],
tsconfig: [paths.appTsConfig, paths.appJsConfig].filter(f =>
fs.existsSync(f),
),
},
},
infrastructureLogging: {
level: 'none',
},
optimization: {
minimize: isEnvProduction,
minimizer: [
// 이것은 프로덕션 모드에서만 사용됩니다.
new TerserPlugin({
terserOptions: {
parse: {
// We want terser to parse ecma 8 code. However, we don't want it
// to apply any minification steps that turns valid ecma 5 code
// into invalid ecma 5 code. This is why the 'compress' and 'output'
// sections only apply transformations that are ecma 5 safe
// https://github.com/facebook/create-react-app/pull/4234
ecma: 8,
},
compress: {
ecma: 5,
warnings: false,
// Disabled because of an issue with Uglify breaking seemingly valid code:
// https://github.com/facebook/create-react-app/issues/2376
// Pending further investigation:
// https://github.com/mishoo/UglifyJS2/issues/2011
comparisons: false,
// Disabled because of an issue with Terser breaking valid code:
// https://github.com/facebook/create-react-app/issues/5250
// Pending further investigation:
// https://github.com/terser-js/terser/issues/120
inline: 2,
},
mangle: {
safari10: true,
},
// Added for profiling in devtools
keep_classnames: isEnvProductionProfile,
keep_fnames: isEnvProductionProfile,
output: {
ecma: 5,
comments: false,
// Turned on because emoji and regex is not minified properly using default
// https://github.com/facebook/create-react-app/issues/2488
ascii_only: true,
},
},
}),
// 이것은 프로덕션 모드에서만 사용됩니다.
new CssMinimizerPlugin(),
],
},
resolve: {
// This allows you to set a fallback for where webpack should look for modules.
// We placed these paths second because we want `node_modules` to "win"
// if there are any conflicts. This matches Node resolution mechanism.
// https://github.com/facebook/create-react-app/issues/253
modules: ['node_modules', paths.appNodeModules].concat(
modules.additionalModulePaths || [],
),
// 노드 생태계가 지원하는 합리적인 기본값입니다.
// 또한 공통 컴포넌트 파일 이름 확장자로 JSX를 포함하여
// 일부 툴은 사용을 권장하지 않지만 다음을 참조하십시오.
// https://github.com/facebook/create-react-app/issues/290
// 보다 나은 지원을 위해 'web' 확장 접두사가 추가되었습니다.
// React Native Web용입니다.
extensions: paths.moduleFileExtensions
.map(ext => `.${ext}`)
.filter(ext => useTypeScript || !ext.includes('ts')),
alias: {
// Support React Native Web
// https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
'@/': path.resolve(__dirname, '../src'),
'react-native': 'react-native-web',
// Allows for better profiling with ReactDevTools
...(isEnvProductionProfile && {
'react-dom$': 'react-dom/profiling',
'scheduler/tracing': 'scheduler/tracing-profiling',
}),
...(modules.webpackAliases || {}),
},
plugins: [
// 사용자가 src/(또는 node_modules/) 외부에서 파일을 가져올 수 없도록 합니다.
// src/ 내에서 babel로만 파일을 처리하기 때문에 이 경우 종종 혼란이 발생합니다.
// 이 문제를 해결하기 위해 src/에서 파일을 가져올 수 없습니다.
// 파일을 node_disclink/에 연결하여 모듈 해상도를 활성화하십시오.
// 소스 파일은 어떤 방식으로도 처리되지 않으므로 컴파일되었는지 확인하십시오.
new ModuleScopePlugin(paths.appSrc, [
paths.appPackageJson,
reactRefreshRuntimeEntry,
reactRefreshWebpackPluginRuntimeEntry,
babelRuntimeEntry,
babelRuntimeEntryHelpers,
babelRuntimeRegenerator,
]),
],
},
module: {
strictExportPresence: true,
rules: [
// 소스 맵을 포함하는 node_modules 패키지를 처리합니다.
shouldUseSourceMap && {
enforce: 'pre',
exclude: /@babel(?:\/|\\{1,2})runtime/,
test: /\.(js|mjs|jsx|ts|tsx|css)$/,
loader: require.resolve('source-map-loader'),
},
{
// "One Of"는 다음 로더를 모두 통과할 때까지
// 요건을 충족합니다. 일치하는 로더가 없으면 로더가 떨어집니다.
// 로더 목록 끝에 있는 "파일" 로더로 돌아갑니다.
oneOf: [
// TODO: 'image/avif'가 mime-db에 있는 경우 이 구성을 병합합니다.
// https://github.com/jshttp/mime-db
{
test: [/\.avif$/],
type: 'asset',
mimetype: 'image/avif',
parser: {
dataUrlCondition: {
maxSize: imageInlineSizeLimit,
},
},
},
// "url" 로더는 "파일" 로더와 같이 기능하지만 자산이 포함되어 있습니다.
// 데이터 URL로 지정된 바이트 수 제한보다 작기 때문에 요청을 피할 수 있습니다.
// 누락된 '테스트'는 일치와 같다.
{
test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
type: 'asset',
parser: {
dataUrlCondition: {
maxSize: imageInlineSizeLimit,
},
},
},
{
test: /\.svg$/,
use: [
{
loader: require.resolve('@svgr/webpack'),
options: {
prettier: false,
svgo: false,
svgoConfig: {
plugins: [{ removeViewBox: false }],
},
titleProp: true,
ref: true,
},
},
{
loader: require.resolve('file-loader'),
options: {
name: 'static/media/[name].[hash].[ext]',
},
},
],
issuer: {
and: [/\.(ts|tsx|js|jsx|md|mdx)$/],
},
},
// Babel로 애플리케이션 JS를 처리합니다.
// 사전 설정에는 JSX, Flow, TypeScript 및 일부 ESnext 기능이 포함됩니다.
{
test: /\.(js|mjs|jsx|ts|tsx)$/,
include: paths.appSrc,
loader: require.resolve('babel-loader'),
options: {
customize: require.resolve(
'babel-preset-react-app/webpack-overrides',
),
presets: [
[
require.resolve('babel-preset-react-app'),
{
runtime: hasJsxRuntime ? 'automatic' : 'classic',
},
],
],
plugins: [
isEnvDevelopment &&
shouldUseReactRefresh &&
require.resolve('react-refresh/babel'),
].filter(Boolean),
// 이는 웹팩용 바벨로더의 기능(바벨 자체가 아님)이다.
// ./node_modules/.cache/babel-loader/에서 결과를 캐시할 수 있습니다.
// 디렉토리로 리빌드 시간을 단축합니다.
cacheDirectory: true,
// cacheCompression을 사용할 수 없는 이유는 #6846을 참조하십시오.
cacheCompression: false,
compact: isEnvProduction,
},
},
// Babel을 사용하여 앱 외부의 JS를 처리합니다.
// 애플리케이션 JS와 달리 표준 ES 기능만 컴파일합니다.
{
test: /\.(js|mjs)$/,
exclude: /@babel(?:\/|\\{1,2})runtime/,
loader: require.resolve('babel-loader'),
options: {
babelrc: false,
configFile: false,
compact: false,
presets: [
[
require.resolve('babel-preset-react-app/dependencies'),
{ helpers: true },
],
],
cacheDirectory: true,
// cacheCompression을 사용할 수 없는 이유는 #6846을 참조하십시오.
cacheCompression: false,
// node_modules로의 디버깅에는 Babel 소스 맵이 필요합니다.
// 코드를 설정합니다. 아래 옵션이 없으면 VSCode와 같은 디버거가 발생합니다.
// 잘못된 코드를 표시하고 잘못된 행에 중단점을 설정합니다.
sourceMaps: shouldUseSourceMap,
inputSourceMap: shouldUseSourceMap,
},
},
// "postcss" 로더는 자동 리픽서를 CSS에 적용합니다.
// "css" 로더는 CSS 내의 경로를 해결하고 의존관계로서 자산을 추가합니다.
// "style" 로더는 CSS를 <style> 태그를 삽입하는 JS 모듈로 변환합니다.
// 실제 가동에서는 MiniCSExtractPlugin을 사용하여 CSS를 추출합니다.
// 개발 시 "스타일" 로더를 사용하여 핫 편집 가능
// CSS의 경우.
// 디폴트로는 확장자가 .module.css인 CSS 모듈을 지원합니다.
{
test: cssRegex,
exclude: cssModuleRegex,
use: getStyleLoaders({
importLoaders: 1,
sourceMap: isEnvProduction
? shouldUseSourceMap
: isEnvDevelopment,
modules: {
mode: 'icss',
},
}),
// Don't consider CSS imports dead code even if the
// containing package claims to have no side effects.
// Remove this when webpack adds a warning or an error for this.
// See https://github.com/webpack/webpack/issues/6571
sideEffects: true,
},
// Adds support for CSS Modules (https://github.com/css-modules/css-modules)
// 확장자 .module.css 사용
{
test: cssModuleRegex,
use: getStyleLoaders({
importLoaders: 1,
sourceMap: isEnvProduction
? shouldUseSourceMap
: isEnvDevelopment,
modules: {
mode: 'local',
getLocalIdent: getCSSModuleLocalIdent,
},
}),
},
// SAS 옵션인 지원(.scss 또는 .sass 확장자를 사용).
// 디폴트로는 SAS 모듈을 지원하고 있습니다.
// extensions .module.scss or .module.sass
{
test: sassRegex,
exclude: sassModuleRegex,
use: getStyleLoaders(
{
importLoaders: 3,
sourceMap: isEnvProduction
? shouldUseSourceMap
: isEnvDevelopment,
modules: {
mode: 'icss',
},
},
'sass-loader',
),
// CSS가 데드코드를 Import하는 것은 고려하지 마십시오.
// 부작용이 없다고 주장하는 포장지가 들어 있습니다.
// 웹 팩에 경고 또는 오류가 추가되면 이 항목을 제거합니다.
// https://github.com/webpack/webpack/issues/6571 를 참조해 주세요.
sideEffects: true,
},
// Adds support for CSS Modules, but using SASS
// using the extension .module.scss or .module.sass
{
test: sassModuleRegex,
use: getStyleLoaders(
{
importLoaders: 3,
sourceMap: isEnvProduction
? shouldUseSourceMap
: isEnvDevelopment,
modules: {
mode: 'local',
getLocalIdent: getCSSModuleLocalIdent,
},
},
'sass-loader',
),
},
// "file" 로더는 이러한 자산이 WebpackDevServer에서 처리되도록 합니다.
// 자산을 「import」하면, 그 (가상) 파일명이 취득됩니다.
// 프로덕션에서 이러한 파일은 빌드 폴더에 복사됩니다.
// 이 로더는 "테스트"를 사용하지 않으므로 모든 모듈을 수신합니다.
// 다른 로더에서 떨어집니다.
{
// 주입 시 "css" 로더가 계속 작동하도록 "js" 파일을 제외합니다.
// 실행 시 "파일" 로더를 통해 처리됩니다.
// 또한 'html' 및 'json' 확장자를 제외하여 처리하도록 합니다.
// 웹 팩 내부 로더에 의해.
exclude: [/^$/, /\.(js|mjs|jsx|ts|tsx)$/, /\.html$/, /\.json$/],
type: 'asset/resource',
},
// ** STOP ** 새 로더를 추가하시겠습니까?
// "파일" 로더 앞에 새 로더를 추가해야 합니다.
],
},
].filter(Boolean),
},
plugins: [
// <script>가 삽입된 'index.html' 파일을 생성합니다.
new HtmlWebpackPlugin(
Object.assign(
{},
{
inject: true,
template: paths.appHtml,
},
isEnvProduction
? {
minify: {
removeComments: true,
collapseWhitespace: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true,
},
}
: undefined,
),
),
// 웹 팩 런타임 스크립트를 인라인합니다. 이 스크립트는 너무 작아서 보증할 수 없습니다.
// 네트워크 요구
// https://github.com/facebook/create-react-app/issues/5358
isEnvProduction &&
shouldInlineRuntimeChunk &&
new InlineChunkHtmlPlugin(HtmlWebpackPlugin, [/runtime-.+[.]js/]),
// 일부 환경 변수를 index.html에서 사용할 수 있도록 합니다.
// 공개 URL은 index.html에서 %PUBLIC_URL%로 사용할 수 있습니다.예:
// <link rel="icon" href=syslogPUBLIC_URL%/favicon.ico">
// "홈 페이지"를 지정하지 않으면 빈 문자열이 됩니다.
// '2011년'에.json. 이 경우 해당 URL의 경로 이름이 됩니다.
new InterpolateHtmlPlugin(HtmlWebpackPlugin, env.raw),
// 이를 통해 모듈을 찾을 수 없는 오류에 필요한 컨텍스트가 제공됩니다.
// 요청 리소스.
new ModuleNotFoundPlugin(paths.appPath),
// 다음과 같은 일부 환경 변수를 JS 코드에서 사용할 수 있도록 합니다.
// if(process.env).NODE_ENV === 'production') {... }. '.env.html'을 참조하십시오.
// NODE_ENV를 상용상태로 설정하는 것은 매우 중요합니다.
// 상용중인 경우.
// 그렇지 않으면 React는 매우 느린 개발 모드로 컴파일됩니다.
new webpack.DefinePlugin(env.stringified),
// React의 실험적인 핫 새로고침.
// https://github.com/facebook/react/tree/main/packages/react-refresh
isEnvDevelopment &&
shouldUseReactRefresh &&
new ReactRefreshWebpackPlugin({
overlay: false,
}),
// 경로에서 케이스를 잘못 입력하면 워처가 제대로 작동하지 않기 때문에
// 이 작업을 시도하면 오류가 출력되는 플러그인이 있습니다.
// See https://github.com/facebook/create-react-app/issues/240
isEnvDevelopment && new CaseSensitivePathsPlugin(),
isEnvProduction &&
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: 'static/css/[name].[contenthash:8].css',
chunkFilename: 'static/css/[name].[contenthash:8].chunk.css',
}),
// Generate an asset manifest file with the following content:
// - "files" key: Mapping of all asset filenames to their corresponding
// output file so that tools can pick it up without having to parse
// `index.html`
// - "entrypoints" key: Array of files which are included in `index.html`,
// can be used to reconstruct the HTML if necessary
new WebpackManifestPlugin({
fileName: 'asset-manifest.json',
publicPath: paths.publicUrlOrPath,
generate: (seed, files, entrypoints) => {
const manifestFiles = files.reduce((manifest, file) => {
manifest[file.name] = file.path;
return manifest;
}, seed);
const entrypointFiles = entrypoints.main.filter(
fileName => !fileName.endsWith('.map'),
);
return {
files: manifestFiles,
entrypoints: entrypointFiles,
};
},
}),
// Moment.js is an extremely popular library that bundles large locale files
// by default due to how webpack interprets its code. This is a practical
// solution that requires the user to opt into importing specific locales.
// https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
// You can remove this if you don't use Moment.js:
new webpack.IgnorePlugin({
resourceRegExp: /^\.\/locale$/,
contextRegExp: /moment$/,
}),
// 프리캐시하여 최신 상태를 유지하는 서비스 워커 스크립트를 생성합니다.
// 웹 팩 빌드의 일부인HTML 및 자산.
isEnvProduction &&
fs.existsSync(swSrc) &&
new WorkboxWebpackPlugin.InjectManifest({
swSrc,
dontCacheBustURLsMatching: /\.[0-9a-f]{8}\./,
exclude: [/\.map$/, /asset-manifest\.json$/, /LICENSE/],
// 사전 설정된 기본 최대 크기(2MB)를 올립니다.
// 로딩이 느린 장애 시나리오를 줄일 수 있습니다.
// See https://github.com/cra-template/pwa/issues/13#issuecomment-722667270
maximumFileSizeToCacheInBytes: 5 * 1024 * 1024,
}),
// TypeScript type checking
useTypeScript &&
new ForkTsCheckerWebpackPlugin({
async: isEnvDevelopment,
typescript: {
typeCheck: {
memoryLimit: 8192,
},
typescriptPath: resolve.sync('typescript', {
basedir: paths.appNodeModules,
}),
configOverwrite: {
compilerOptions: {
sourceMap: isEnvProduction
? shouldUseSourceMap
: isEnvDevelopment,
skipLibCheck: true,
inlineSourceMap: false,
declarationMap: false,
noEmit: true,
incremental: true,
tsBuildInfoFile: paths.appTsBuildInfoFile,
},
},
context: paths.appPath,
diagnosticOptions: {
syntactic: true,
},
mode: 'write-references',
// profile: true,
},
issue: {
// This one is specifically to match during CI tests,
// as micromatch doesn't match
// '../cra-template-typescript/template/src/App.tsx'
// otherwise.
include: [
{ file: '../**/src/**/*.{ts,tsx}' },
{ file: '**/src/**/*.{ts,tsx}' },
],
exclude: [
{ file: '**/src/**/__tests__/**' },
{ file: '**/src/**/?(*.){spec|test}.*' },
{ file: '**/src/setupProxy.*' },
{ file: '**/src/setupTests.*' },
],
},
logger: {
infrastructure: 'silent',
},
}),
// !disableESLintPlugin &&
// new ESLintPlugin({
// // Plugin options
// extensions: ['js', 'mjs', 'jsx', 'ts', 'tsx'],
// formatter: require.resolve('react-dev-utils/eslintFormatter'),
// eslintPath: require.resolve('eslint'),
// failOnError: !(isEnvDevelopment && emitErrorsAsWarnings),
// context: paths.appSrc,
// cache: true,
// cacheLocation: path.resolve(
// paths.appNodeModules,
// '.cache/.eslintcache',
// ),
// // ESLint class options
// cwd: paths.appPath,
// resolvePluginsRelativeTo: __dirname,
// baseConfig: {
// extends: [require.resolve('eslint-config-react-app/base')],
// rules: {
// ...(!hasJsxRuntime && {
// 'react/react-in-jsx-scope': 'error',
// }),
// },
// },
// }),
].filter(Boolean),
// Turn off performance processing because we utilize
// our own hints via the FileSizeReporter
performance: false,
};
};