blog

webpackベースのReactパッケージングツールを書く (2)

webpackの設定は、webpackのパッケージであり、2つのコマンドは、いくつかの公開設定があり、公開設定は、ファイルに書かれています。...

Oct 26, 2020 · 8 min. read
シェア

webpackの設定

webpack.common.js
webpack.dev.js
webpack.prod.js
webpack.umdcommon.js
webpack.umd.js

startapp.jsとbuildapp.jsはどちらもwebpackのラッパーで、公開設定があります。公開設定はwebpack.common.jsファイルに書かれています。

webpack.common.js

const path = require('path'); const webpack = require('webpack'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const CopyWebpackPlugin = require('copy-webpack-plugin'); const HappyPack = require('happypack'); const WebpackBar = require('webpackbar'); const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin'); const runtimePath = process.argv[8]; const APP_PATH = path.resolve(runtimePath, 'src'); // プロジェクトのsrcディレクトリ const { getPostCssConfigPath } = require('../util'); module.exports = { plugins: { HtmlWebpackPlugin, MiniCssExtractPlugin, CopyWebpackPlugin, }, config: { /** * */ entry: { index: path.join(runtimePath, 'src', 'index.js'), }, /** * */ output: { filename: process.env.NODE_ENV === 'production' ? '[name].[chunkhash].bundle.js' : '[name].[hash].bundle.js', chunkFilename: process.env.NODE_ENV === 'production' ? '[name].[chunkhash].bundle.js' : '[name].[hash].bundle.js', path: path.resolve(runtimePath, 'dist'), publicPath: '/', }, plugins: [ // html new HtmlWebpackPlugin({ title: '', // テンプレートhtmlタイトル filename: 'index.html', // テンプレート名 template: path.join(runtimePath, 'src', 'index.html'),// テンプレートのアドレス hash: true, // キャッシュを防ぐ minify: { removeAttributeQuotes: true, // 圧縮する 引用符を削除する }, chunks: ['index'], }), // このプラグインは、モジュールの相対パスに基づいて4桁のハッシュをモジュールIDとして生成する。 new webpack.HashedModuleIdsPlugin(), // cssを別ファイルにする new MiniCssExtractPlugin({ filename: '[name].css', chunkFilename: '[id].css', ignoreOrder: false, // Enable to remove warnings about conflicting order }), // TypeScriptタイプチェッカーのwebpackプラグインを別プロセスで実行する new ForkTsCheckerWebpackPlugin({ tsconfig: path.join(runtimePath, 'tsconfig.json'), checkSyntacticErrors: true, }), // jsxとjs babelのパース new HappyPack({ id: 'babel', loaders: [ 'cache-loader', { loader: 'babel-loader', query: { presets: [ [ '@babel/preset-env', { useBuiltIns: 'usage', // polyfillにcorejs3を使う corejs: { version: 3, proposals: true }, }, ], '@babel/preset-react', ], plugins: [ '@babel/plugin-transform-runtime', '@babel/plugin-syntax-dynamic-import', '@babel/plugin-proposal-function-bind', '@babel/plugin-proposal-class-properties', ], }, }, ], }), // tstsxで解析する new HappyPack({ id: 'ts', loaders: [ { loader: 'ts-loader', options: { transpileOnly: true, happyPackMode: true, configFile: path.join(runtimePath, 'tsconfig.json'), }, }, ], }), // css new HappyPack({ id: 'css', loaders: [ 'cache-loader', { loader: 'css-loader', options: { importLoaders: 1, }, }, { loader: 'postcss-loader', options: { config: { path: getPostCssConfigPath(runtimePath), }, }, }, ], }), // less new HappyPack({ id: 'less', loaders: [ 'cache-loader', { loader: 'css-loader', options: { importLoaders: 1, }, }, { loader: 'postcss-loader', options: { config: { path: getPostCssConfigPath(runtimePath), }, }, }, { loader: 'less-loader', query: { javascriptEnabled: true, }, }, ], }), new WebpackBar({ reporters: ['profile'], profile: true }), ], optimization: { runtimeChunk: 'single', splitChunks: { cacheGroups: { vendor: { test: /[\\/]node_modules[\\/]/, name: 'vendors', chunks: 'all', }, }, }, }, module: { rules: [ { test: /\.m?jsx?$/, exclude: /(node_modules|bower_components)/, include: [APP_PATH], use: ['happypack/loader?id=babel'], }, { test: /\.m?tsx?$/, exclude: /(node_modules|bower_components)/, include: [APP_PATH], use: ['happypack/loader?id=ts'], }, { test: /\.css$/, include: [ APP_PATH, /highlight.js/, /photoswipe.css/, /default-skin.css/, /swiper.min.css/, /antd/, /antd-mobile/, /normalize.css/, ], use: [ process.env.NODE_ENV === 'development' ? 'style-loader' : MiniCssExtractPlugin.loader, 'happypack/loader?id=css', ], }, { test: /\.less$/, include: [APP_PATH, /normalize.less/], use: [ process.env.NODE_ENV === 'development' ? 'style-loader' : MiniCssExtractPlugin.loader, 'happypack/loader?id=less', ], }, { test: /\.(png|svg|jpg|gif|ico)$/, use: [ { loader: 'url-loader', options: { limit: 1024, }, }, ], }, { test: /\.(woff|woff2|eot|ttf|otf)$/, use: [ { loader: 'url-loader', options: { limit: 1024, }, }, ], }, { test: /\.(csv|tsv)$/, use: ['csv-loader'], }, { test: /\.xml$/, use: ['xml-loader'], }, { test: /\.ejs/, loader: ['ejs-loader?variable=data'], }, { test: /\.ya?ml$/, use: ['json-loader', 'yaml-loader'], }, ], }, resolve: { extensions: ['.js', '.jsx', '.ts', '.tsx', '.less', '.css', '.json'], // サフィックスの自動補完 }, }, }; // postcssの設定時にpostcssを探す.config.js設定ファイル getPostCssConfigPath(runtimePath) { if (fs.existsSync(path.join(runtimePath, 'postcss.config.js'))) { return path.join(runtimePath, 'postcss.config.js'); } return path.join(__dirname, 'postcss.config.js'); }

多くのローダーやプラグインの使用の公開設定では、また、最適化のローダー部分に、happypackの主な使用のこの部分の最適化が、また、少ない解像度に追加されますが、また、オートプレフィクサの操作のためのpostcss-loaderの使用は、他の構成は、基本的な構成のいくつかであり、ここではこれ以上行いません!ここではこれ以上説明しません。説明する必要があるのは、ファイルが2つのキーをエクスポートすることです、それぞれ、プラグインと設定

この公開ファイルが書き込まれたら、次のステップはdevとprodの設定ファイルを実装することです。

webpack.dev.js

const webpack = require('webpack');
const merge = require('webpack-merge');
const common = require('./webpack.common.js');
const commandArgs = require('../commandArgs');
const argsMap = commandArgs.initCommandArgs();
const customConfigPath = argsMap.get('--customconfig')[0];
let customModule;
const curModule = merge(common.config, {
 mode: 'development',
 devtool: 'cheap-module-eval-source-map',
 devServer: {
 publicPath: '/',
 host: 'localhost',
 compress: true,
 port: 8000,
 clientLogLevel: 'none', //面倒な出力はもういらない
 historyApiFallback: true,
 overlay: true, //ブラウザの全画面エラーメッセージ
 hot: true, // モジュールのホットアップデートHMRを開始する
 open: true, // ブラウザの自動ページオープンを有効にする
 },
 plugins: [
 new webpack.DefinePlugin({
 process: {
 env: {
 NODE_ENV: JSON.stringify('development'),
 REAP_PATH: JSON.stringify(process.env.REAP_PATH),
 },
 },
 }),
 new webpack.NamedModulesPlugin(),
 new webpack.HotModuleReplacementPlugin(),
 ],
});
const define = argsMap.get('--define')[0] || '';
if (customConfigPath) {
 customModule = require(customConfigPath);
 if (customModule && customModule.getConfig) {
 customModule.getConfig({
 webpack,
 curModule,
 plugins: common.plugins,
 define: commandArgs.toCommandArgs(define),
 });
 }
}
module.exports = curModule;

開発環境は、主にwebpack-dev-serverの設定で、ここで個別にパラメータを設定します。

webpack.prod.js

const webpack = require('webpack');
const merge = require('webpack-merge');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const common = require('./webpack.common.js');
const commandArgs = require('../commandArgs');
const argsMap = commandArgs.initCommandArgs();
const customConfigPath = argsMap.get('--customconfig')[0];
let customModule;
const curModule = merge(common.config, {
 mode: 'production',
 plugins: [
 new CleanWebpackPlugin(),
 new webpack.DefinePlugin({
 process: {
 env: {
 NODE_ENV: JSON.stringify('production'),
 REAP_PATH: JSON.stringify(process.env.REAP_PATH),
 },
 },
 }),
 ],
});
const define = argsMap.get('--define')[0] || '';
if (customConfigPath) {
 customModule = require(customConfigPath);
 if (customModule && customModule.getConfig) {
 customModule.getConfig({
 webpack,
 curModule,
 plugins: common.plugins,
 define: commandArgs.toCommandArgs(define),
 });
 }
}
module.exports = curModule;

プロッド環境はここで個別にパラメータ化されます。

それは最終的にcustomCinfigPathパス内のパラメータを探しますdevまたはprodであるかどうか、ユーザーの設定ファイル、ユーザーがこのパラメータを渡さなかった場合、それはctbuild.config.jsこの設定ファイルを探しますが、ここではWebpackになり、現在の設定、すべてのプラグインやその他のコマンドラインパラメータに渡されます。getConfigメソッドは、変更のために渡された設定の設定ファイルのユーザーは、カスタム設定の効果を達成するために。

まず最初に、webpack.dev.jsとwebpack.prod.jsはpackgeプロジェクトではなくホストプロジェクトをコンパイルするものであることを理解してください。fork-ts-checker-webpack-pluginプラグインを使って解析します。

babel.config.jsファイルの導入の次に、このファイルは、バベルの構文解析を設定するために使用され、この設定ファイルは、パッケージプロジェクトのルートディレクトリに配置され、startapp、buildappとbuildpackageの実行でこのファイルが使用されます。

babel.config.js

const presets = [
 [
 '@babel/preset-env',
 {
 // polyfillの前にパターンを使う。
 useBuiltIns: 'usage',
 // polyfillにcorejs3を使う
 corejs: { version: 3, proposals: true },
 },
 ],
 '@babel/preset-react',
];
const plugins = [
 '@babel/plugin-transform-runtime',
 '@babel/plugin-syntax-dynamic-import',
 '@babel/plugin-proposal-function-bind',
 '@babel/plugin-proposal-optional-chaining',
 // デコレーターパターンを使う
 ['@babel/plugin-proposal-decorators', { legacy: true }],
 ['@babel/plugin-proposal-class-properties', { loose: true }],
];
module.exports = { presets, plugins };

Read next

Linuxの基本

. → bn と :bp → 同時にたくさんのファイルを開くことができます。 help → コマンドのヘルプを表示します。コマンドの後に続けずに、:help とだけ入力することもできます。 w → 次の単語の先頭に移動します。 ...

Oct 26, 2020 · 6 min read