0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

eject後のwebpack.config.jsを1から読み解いてみる②

Posted at

はじめに

この記事は前回の記事の続きです。前回の記事を見ていない方はこちらからご覧ください。

Ln274-Ln320

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 || []
  ),
  // These are the reasonable defaults supported by the Node ecosystem.
  // We also include JSX as a common component filename extension to support
  // some tools, although we do not recommend using it, see:
  // https://github.com/facebook/create-react-app/issues/290
  // `web` extension prefixes have been added for better support
  // for 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/
    '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: [
    // Adds support for installing with Plug'n'Play, leading to faster installs and adding
    // guards against forgotten dependencies and such.
    PnpWebpackPlugin,
    // Prevents users from importing files from outside of src/ (or node_modules/).
    // This often causes confusion because we only process files within src/ with babel.
    // To fix this, we prevent you from importing files out of src/ -- if you'd like to,
    // please link the files into your node_modules/ and let module-resolution kick in.
    // Make sure your source files are compiled, as they will not be processed in any way.
    new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
  ],
},

resolveではmoduleの取り扱いに関する設定を行います。
・modules
 どこのディレクトリにあるmoduleを利用するかを指定する。

・extensions
 moduleの読み込みのときに補完できる拡張子を設定する。
 .jsが含まれていたらrequire('a')としたときa.jsを読み込むことができるようになる。

・alias
 moduleを呼び出したときに参照するパスの設定を行う。
 基本は'a': 'b'require('a')としたときbの直下を読む。

・plugins
 moduleの解決時に追加で用いるpluginの設定。
 PnpWebpackPlugin: 詳しい説明なかったけどnode_modulesの解決を簡略化するらしい。
 ModuleScopePlugin: srcより外からのインポートを禁止する。(node_modulesは許可)

resolveLoader: {
  plugins: [
    // Also related to Plug'n'Play, but this time it tells webpack to load its loaders
    // from the current package.
    PnpWebpackPlugin.moduleLoader(module),
  ],
},

loaderの取り扱いについての設定
内容はresolveと同様

Ln321-Ln509

module: {
  strictExportPresence: true,
  rules: [
    // Disable require.ensure as it's not a standard language feature.
    { parser: { requireEnsure: false } },
    // First, run the linter.
    // It's important to do this before Babel processes the JS.
    {
      test: /\.(js|mjs|jsx|ts|tsx)$/,
      enforce: 'pre',
      use: [
        {
          options: {
            cache: true,
            formatter: require.resolve('react-dev-utils/eslintFormatter'),
            eslintPath: require.resolve('eslint'),
            resolvePluginsRelativeTo: __dirname,
            
          },
          loader: require.resolve('eslint-loader'),
        },
      ],
      include: paths.appSrc,
    },
    {
      // "oneOf" will traverse all following loaders until one will
      // match the requirements. When no loader matches it will fall
      // back to the "file" loader at the end of the loader list.
      oneOf: [
        // "url" loader works like "file" loader except that it embeds assets
        // smaller than specified limit in bytes as data URLs to avoid requests.
        // A missing `test` is equivalent to a match.
        {
          test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
          loader: require.resolve('url-loader'),
          options: {
            limit: imageInlineSizeLimit,
            name: 'static/media/[name].[hash:8].[ext]',
          },
        },
        // Process application JS with Babel.
        // The preset includes JSX, Flow, TypeScript, and some ESnext features.
        {
          test: /\.(js|mjs|jsx|ts|tsx)$/,
          include: paths.appSrc,
          loader: require.resolve('babel-loader'),
          options: {
            customize: require.resolve(
              'babel-preset-react-app/webpack-overrides'
            ),
            
            plugins: [
              [
                require.resolve('babel-plugin-named-asset-import'),
                {
                  loaderMap: {
                    svg: {
                      ReactComponent:
                        '@svgr/webpack?-svgo,+titleProp,+ref![path]',
                    },
                  },
                },
              ],
            ],
            // This is a feature of `babel-loader` for webpack (not Babel itself).
            // It enables caching results in ./node_modules/.cache/babel-loader/
            // directory for faster rebuilds.
            cacheDirectory: true,
            // See #6846 for context on why cacheCompression is disabled
            cacheCompression: false,
            compact: isEnvProduction,
          },
        },
        // Process any JS outside of the app with Babel.
        // Unlike the application JS, we only compile the standard ES features.
        {
          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,
            // See #6846 for context on why cacheCompression is disabled
            cacheCompression: false,
            
            // Babel sourcemaps are needed for debugging into node_modules
            // code.  Without the options below, debuggers like VSCode
            // show incorrect code and set breakpoints on the wrong lines.
            sourceMaps: shouldUseSourceMap,
            inputSourceMap: shouldUseSourceMap,
          },
        },
        // "postcss" loader applies autoprefixer to our CSS.
        // "css" loader resolves paths in CSS and adds assets as dependencies.
        // "style" loader turns CSS into JS modules that inject <style> tags.
        // In production, we use MiniCSSExtractPlugin to extract that CSS
        // to a file, but in development "style" loader enables hot editing
        // of CSS.
        // By default we support CSS Modules with the extension .module.css
        {
          test: cssRegex,
          exclude: cssModuleRegex,
          use: getStyleLoaders({
            importLoaders: 1,
            sourceMap: isEnvProduction && shouldUseSourceMap,
          }),
          // 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)
        // using the extension .module.css
        {
          test: cssModuleRegex,
          use: getStyleLoaders({
            importLoaders: 1,
            sourceMap: isEnvProduction && shouldUseSourceMap,
            modules: {
              getLocalIdent: getCSSModuleLocalIdent,
            },
          }),
        },
        // Opt-in support for SASS (using .scss or .sass extensions).
        // By default we support SASS Modules with the
        // extensions .module.scss or .module.sass
        {
          test: sassRegex,
          exclude: sassModuleRegex,
          use: getStyleLoaders(
            {
              importLoaders: 3,
              sourceMap: isEnvProduction && shouldUseSourceMap,
            },
            'sass-loader'
          ),
          // 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, but using SASS
        // using the extension .module.scss or .module.sass
        {
          test: sassModuleRegex,
          use: getStyleLoaders(
            {
              importLoaders: 3,
              sourceMap: isEnvProduction && shouldUseSourceMap,
              modules: {
                getLocalIdent: getCSSModuleLocalIdent,
              },
            },
            'sass-loader'
          ),
        },
        // "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.
      ],
    },
  ],
},

長いですが内容はほぼ同じなので一気にいきます。
moduleはファイルの取り扱い(loaderを使うか)を決めます。

・strictExportPresence
 ファイルのエクスポートがないときに呼ばれてるかに関わらずエラーにする。

・rules
 どのloaderをどのファイルに当てるかの設定。
 parser: 標準対応されていないrequire.ensureを無効化する。
 (bundleファイルの分け方に関する設定らしい)
 test: 設定を適用するファイルの正規表現。
 use: どのloaderを使うか。useでなくloaderを使って直接書くこともできるが、useを使うことでoptionなども指定できる。
 enforce: loaderの分類。
 include: 条件に合うものも設定を適用する
 exclude: 条件に合うものには設定を適用しない
 oneof: 複数のruleの中で最初に条件に合ったもののみ適用する

ここで扱われてるloader
・eslint-loader
oneof [
 ・url-loader
 ・bable-loader
 ・getStyleLoaders(Ln71~Ln129で指定されていた内容)
 ・file-loader
]

個々のloaderについては前回触れたものも多いので省略します。もし必要そうだったら別で記事を書くかもしれないです。

Ln510-Ln652

plugins: [
  // Generates an `index.html` file with the <script> injected.
  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
    )
  ),
  // Inlines the webpack runtime script. This script is too small to warrant
  // a network request.
  // https://github.com/facebook/create-react-app/issues/5358
  isEnvProduction &&
    shouldInlineRuntimeChunk &&
    new InlineChunkHtmlPlugin(HtmlWebpackPlugin, [/runtime-.+[.]js/]),
  // Makes some environment variables available in index.html.
  // The public URL is available as %PUBLIC_URL% in index.html, e.g.:
  // <link rel="icon" href="%PUBLIC_URL%/favicon.ico">
  // It will be an empty string unless you specify "homepage"
  // in `package.json`, in which case it will be the pathname of that URL.
  new InterpolateHtmlPlugin(HtmlWebpackPlugin, env.raw),
  // This gives some necessary context to module not found errors, such as
  // the requesting resource.
  new ModuleNotFoundPlugin(paths.appPath),
  // Makes some environment variables available to the JS code, for example:
  // if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`.
  // It is absolutely essential that NODE_ENV is set to production
  // during a production build.
  // Otherwise React will be compiled in the very slow development mode.
  new webpack.DefinePlugin(env.stringified),
  // This is necessary to emit hot updates (currently CSS only):
  isEnvDevelopment && new webpack.HotModuleReplacementPlugin(),
  // Watcher doesn't work well if you mistype casing in a path so we use
  // a plugin that prints an error when you attempt to do this.
  // See https://github.com/facebook/create-react-app/issues/240
  isEnvDevelopment && new CaseSensitivePathsPlugin(),
  // If you require a missing module and then `npm install` it, you still have
  // to restart the development server for webpack to discover it. This plugin
  // makes the discovery automatic so you don't have to restart.
  // See https://github.com/facebook/create-react-app/issues/186
  isEnvDevelopment &&
    new WatchMissingNodeModulesPlugin(paths.appNodeModules),
  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 ManifestPlugin({
    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(/^\.\/locale$/, /moment$/),
  // Generate a service worker script that will precache, and keep up to date,
  // the HTML & assets that are part of the webpack build.
  isEnvProduction &&
    new WorkboxWebpackPlugin.GenerateSW({
      clientsClaim: true,
      exclude: [/\.map$/, /asset-manifest\.json$/],
      importWorkboxFrom: 'cdn',
      navigateFallback: paths.publicUrlOrPath + 'index.html',
      navigateFallbackBlacklist: [
        // Exclude URLs starting with /_, as they're likely an API call
        new RegExp('^/_'),
        // Exclude any URLs whose last part seems to be a file extension
        // as they're likely a resource and not a SPA route.
        // URLs containing a "?" character won't be blacklisted as they're likely
        // a route with query params (e.g. auth callbacks).
        new RegExp('/[^/?]+\\.[^/]+$'),
      ],
    }),
  // TypeScript type checking
  useTypeScript &&
    new ForkTsCheckerWebpackPlugin({
      typescript: resolve.sync('typescript', {
        basedir: paths.appNodeModules,
      }),
      async: isEnvDevelopment,
      useTypescriptIncrementalApi: true,
      checkSyntacticErrors: true,
      resolveModuleNameModule: process.versions.pnp
        ? `${__dirname}/pnpTs.js`
        : undefined,
      resolveTypeReferenceDirectiveModule: process.versions.pnp
        ? `${__dirname}/pnpTs.js`
        : undefined,
      tsconfig: paths.appTsConfig,
      reportFiles: [
        '**',
        '!**/__tests__/**',
        '!**/?(*.)(spec|test).*',
        '!**/src/setupProxy.*',
        '!**/src/setupTests.*',
      ],
      silent: true,
      // The formatter is invoked directly in WebpackDevServerUtils during development
      formatter: isEnvProduction ? typescriptFormatter : undefined,
    }),
].filter(Boolean),

拡張プラグインの設定。
設定されているプラグインは以下

#####常に使用
・HtmlWebpackPlugin
 htmlファイルをひとまとめにする。

・InterpolateHtmlPlugin
 bundleするhtmlファイルで変数を使えるようにする。

・ModuleNotFoundPlugin
 インポートするファイルが見つからなかったときのエラーを設定する。

・webpack.DefinePlugin
 グローバル変数を設定する。

・ManifestPlugin
 manifest.jsonを生成し、ライブラリの参照先を指定する。
 
・webpack.IgnorePlugin
 特定のファイルをインポートしないようにする。

#####開発環境のみで使用
・webpack.HotModuleReplacementPlugin
 hot module replacement(起動中にファイルを切り替えることで処理を高速化する)を利用できるようにする。

・CaseSensitivePathsPlugin
 インポートファイルのパスの大文字小文字を区別する。

・WatchMissingNodeModulesPlugin
 依存しているライブラリがインストールされていないときにインストールする

#####本番環境のみで使用
・InlineChunkHtmlPlugin (shouldInlineRuntimeChunk(Ln36)がtrueのとき)
 共通の設定をChunkの中に埋め込み、http通信の数を減らすことができる。

・MiniCssExtractPlugin
 CSSを別ファイルに分離してまとめる。

・WorkboxWebpackPlugin
 ページのキャッシングを行う。

#####TypeScript使用時(useTypeScript(Ln45)がtrueのとき)のみ使用
・ForkTsCheckerWebpackPlugin
 Typescriptの型判定を高速化する。

Ln653-Ln669

// Some libraries import Node modules but don't use them in the browser.
// Tell webpack to provide empty mocks for them so importing them works.
node: {
  module: 'empty',
  dgram: 'empty',
  dns: 'mock',
  fs: 'empty',
  http2: 'empty',
  net: 'empty',
  tls: 'empty',
  child_process: 'empty',
},
// Turn off performance processing because we utilize
// our own hints via the FileSizeReporter
performance: false,

node
nodeの設定。呼ばれるが実際使われないものについて空のオブジェクトを返す。

performance
bundleしたファイルサイズが指定を超えた場合にアラートを出すかの設定。

終わりに

後半大分駆け足でしたがなんとかwebpackの設定を読み切ることができました!
eject時には設定されていない内容もあるし、出てきたものも細かい使い方を理解できたわけではありませんがこの記事を書いたことでwebpackでどういったことができるのかがなんとなくつかめたかなと思います。

今後新しく気づきがあればこの記事も追記させていただきます。いろいろ調べながら書いたものの理解できていない部分もあるので間違っている部分などがあれば指摘していただけるとありがたいです

参考ページ

全体
https://webpack.js.org/
http://js.studio-kingdom.com/webpack/api/configuration
https://qiita.com/soarflat/items/28bf799f7e0335b68186
https://site-builder.wiki/posts/9654

module
https://yuhodev.hatenablog.com/entry/2019/07/13/165518
https://qiita.com/s4kr4/items/c6f0e8278844117502cc#modulestrictexportpresence
https://www.slideshare.net/ssuserc9c8d8/reactscriptswebpack-130687608

HtmlWebpackPlugin
https://ema-hiro.hatenablog.com/entry/2017/10/12/015748

InterpolateHtmlPlugin
https://spectrum.chat/create-react-app/general/how-to-use-interpolatehtmlplugin-on-multiple-html-pages~d4fdc579-86cd-4d46-9503-33088c037164

ManifestPlugin
https://www.npmjs.com/package/webpack-manifest-plugin

WorkboxWebpackPlugin
https://developers.google.com/web/tools/workbox/modules/workbox-webpack-plugin

ForkTsCheckerWebpackPlugin
https://www.npmjs.com/package/fork-ts-checker-webpack-plugin

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?