generated from DonAdam2/webpack-react-boilerplate
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathwebpack.common.js
236 lines (233 loc) · 8.12 KB
/
webpack.common.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
/* eslint-disable @typescript-eslint/no-require-imports */
const NodePolyfillPlugin = require('node-polyfill-webpack-plugin'),
path = require('path'),
//plugins
HtmlWebpackPlugin = require('html-webpack-plugin'),
MiniCssExtractPlugin = require('mini-css-extract-plugin'),
EsLintPlugin = require('eslint-webpack-plugin'),
//runs TypeScript type checker on a separate process, which speeds up webpack compilation time.
ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin'),
//constants
{
devServer,
jsSubDirectory,
isCssModules,
metaInfo: { title, description, keywords, siteName, twitterCardType },
} = require('./constants'),
{
publicDirPath,
srcPath,
outputSrcPath,
jestPath,
appIndexPath,
tsDirectoryPath,
stylesDirectoryPath,
indexHtmlPath,
} = require('./paths'),
//helpers
{ generateScopedName } = require('./helpers');
module.exports = (env, options) => {
// the mode variable is passed in package.json scripts (development, production)
const isDevelopment = options.mode === 'development';
return {
entry: appIndexPath,
output: {
path: outputSrcPath,
// hashes are very important in production for caching purposes
filename: jsSubDirectory + '[name].[contenthash:8].js',
// used for the lazy loaded component
chunkFilename: jsSubDirectory + 'chunk.[contenthash:8].js',
publicPath: '/',
assetModuleFilename: (pathData) => {
//allows us to have the same folder structure of assets as we have it in /public
const filepath = path.dirname(pathData.filename).split('/').slice(1).join('/');
return `${filepath}/[name].[hash][ext][query]`;
},
},
optimization: {
// used to avoid duplicated dependencies from node modules
runtimeChunk: 'single',
splitChunks: {
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendor',
enforce: true,
chunks: 'all',
},
},
},
},
resolve: {
extensions: ['.js', '.ts', '.tsx', '.json'],
// declaring aliases to reduce the use of relative path
alias: {
'@/jest': jestPath,
'@/ts': tsDirectoryPath,
'@/scss': stylesDirectoryPath,
'@/public': publicDirPath,
},
},
module: {
rules: [
{
test: /\.(ts|js)x?$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: {
// 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,
cacheCompression: false,
compact: !isDevelopment,
},
},
{
//required for ForkTsCheckerWebpackPlugin
loader: 'ts-loader',
},
],
},
{
test: /\.(jpe?g|svg|png|gif|ico|eot|ttf|woff2?)(\?v=\d+\.\d+\.\d+)?$/i,
type: 'asset/resource',
},
{
test: /\.s?[ac]ss$/,
//removed (exclude: /node_modules/) to enable using external styles
use: [
{
// style-loader => insert styles in the head of the HTML as style tags or in blob links
// MiniCssExtractPlugin => extract styles to a file
loader: isDevelopment ? 'style-loader' : MiniCssExtractPlugin.loader,
//if source map is set to true from previous loaders => this loader will be true as well
},
{
//Resolves @import statements
loader: 'css-loader',
options: {
// used for debugging the app (to see from which component styles are applied)
sourceMap: isDevelopment,
// Number of loaders applied before CSS loader (which is postcss-loader)
importLoaders: 3,
// the following is used to enable CSS modules
...(isCssModules
? {
modules: {
//exclude external styles from css modules transformation
auto: (resourcePath) => !resourcePath.includes('node_modules'),
mode: (resourcePath) =>
/global.scss$/i.test(resourcePath) ? 'global' : 'local',
...(isDevelopment
? {
//e.g. box_box-wrapper
localIdentName: '[name]_[local]',
}
: {
//e.g. b_i
getLocalIdent: (context, localIdentName, localName) => {
return generateScopedName(localName, context.resourcePath);
},
}),
localIdentContext: srcPath,
localIdentHashSalt: 'react-boilerplate',
exportLocalsConvention: 'camel-case-only',
namedExport: false,
},
}
: {}),
},
},
{
loader: 'postcss-loader',
options: {
postcssOptions: {
ident: 'postcss',
plugins: [
'postcss-flexbugs-fixes',
[
'postcss-preset-env',
{
stage: 0,
//uncomment the following if you want to prefix grid properties
// autoprefixer: { grid: true },
},
],
// Adds PostCSS Normalize as the reset css with default options,
// so that it honors browserslist config in package.json
// which in turn let's users customize the target behavior as per their needs.
'postcss-normalize',
],
},
sourceMap: isDevelopment,
},
},
{
//Rewrites relative paths in url() statements based on the original source file
loader: 'resolve-url-loader',
options: {
//needs sourcemaps to resolve urls (images)
sourceMap: true,
},
},
{
//Compiles Sass to CSS
loader: 'sass-loader',
options: {
sourceMap: true,
},
},
],
},
],
},
plugins: [
new EsLintPlugin({
extensions: ['.js', '.ts', '.tsx', '.json'],
}),
new ForkTsCheckerWebpackPlugin({ async: isDevelopment }),
new HtmlWebpackPlugin(
Object.assign(
{},
{
inject: true,
template: indexHtmlPath,
title,
filename: 'index.html',
meta: {
title,
description,
keywords,
siteName,
'twitter:card': twitterCardType,
//coming from scripts/start.js file
...(isDevelopment && { url: `${devServer}:${options.port}` }),
'apple-mobile-web-app-capable': 'yes',
'mobile-web-app-capable': 'yes',
},
},
!isDevelopment
? {
minify: {
removeComments: true,
collapseWhitespace: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true,
},
}
: undefined
)
),
new NodePolyfillPlugin(),
],
};
};