Разделены конфигурации webpack

This commit is contained in:
goodmice 2022-10-05 15:28:27 +05:00
parent 8db523b6de
commit 84204ab146
No known key found for this signature in database
GPG Key ID: 63EA771203189CF1
10 changed files with 3840 additions and 156 deletions

4
.gitignore vendored
View File

@ -11,8 +11,10 @@
# testing # testing
/coverage /coverage
# production # build directories
/build /build
/dev_build
/prod_build
# misc # misc
.DS_Store .DS_Store

3518
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -16,10 +16,15 @@
"web-vitals": "^2.1.4" "web-vitals": "^2.1.4"
}, },
"scripts": { "scripts": {
"start": "webpack-dev-server --mode=development --open --hot",
"build": "webpack --mode=production",
"test": "jest", "test": "jest",
"dev": "webpack-dev-server --mode=development --open --hot", "build": "webpack --env=\"ENV=prod\"",
"dev_build": "webpack --env=\"ENV=dev\"",
"prod_build": "webpack --env=\"ENV=prod\"",
"start": "webpack-dev-server --env=\"ENV=dev\" --open --hot",
"prod": "webpack-dev-server --env=\"ENV=prod\" --open --hot",
"dev": "webpack-dev-server --env=\"ENV=dev\" --open --hot",
"oul": "npx openapi -i http://127.0.0.1:5000/swagger/v1/swagger.json -o src/services/api", "oul": "npx openapi -i http://127.0.0.1:5000/swagger/v1/swagger.json -o src/services/api",
"oud": "npx openapi -i http://192.168.1.113:5000/swagger/v1/swagger.json -o src/services/api", "oud": "npx openapi -i http://192.168.1.113:5000/swagger/v1/swagger.json -o src/services/api",
"oug": "npx openapi -i https://cloud.digitaldrilling.ru/swagger/v1/swagger.json -o src/services/api", "oug": "npx openapi -i https://cloud.digitaldrilling.ru/swagger/v1/swagger.json -o src/services/api",
@ -84,24 +89,30 @@
"@types/react-router-dom": "^5.3.3", "@types/react-router-dom": "^5.3.3",
"babel-jest": "^28.1.0", "babel-jest": "^28.1.0",
"babel-loader": "^8.2.5", "babel-loader": "^8.2.5",
"colors": "^1.4.0",
"css-loader": "^6.7.1", "css-loader": "^6.7.1",
"css-minimizer-webpack-plugin": "^4.2.0",
"extract-loader": "^5.1.0",
"file-loader": "^6.2.0", "file-loader": "^6.2.0",
"html-webpack-plugin": "^5.5.0", "html-webpack-plugin": "^5.5.0",
"interpolate-html-plugin": "^4.0.0", "interpolate-html-plugin": "^4.0.0",
"jest": "^28.1.0", "jest": "^28.1.0",
"less": "^4.1.3", "less": "^4.1.3",
"less-loader": "^11.0.0", "less-loader": "^11.0.0",
"mini-css-extract-plugin": "^2.6.1",
"openapi-typescript": "^5.4.0", "openapi-typescript": "^5.4.0",
"openapi-typescript-codegen": "^0.23.0", "openapi-typescript-codegen": "^0.23.0",
"path-browserify": "^1.0.1", "path-browserify": "^1.0.1",
"react-test-renderer": "^18.1.0", "react-test-renderer": "^18.1.0",
"source-map-loader": "^3.0.1", "source-map-loader": "^3.0.1",
"style-loader": "^3.3.1", "style-loader": "^3.3.1",
"terser-webpack-plugin": "^5.3.6",
"ts-loader": "^9.3.0", "ts-loader": "^9.3.0",
"typescript": "^4.7.4", "typescript": "^4.7.4",
"url-loader": "^4.1.1", "url-loader": "^4.1.1",
"webpack": "^5.73.0", "webpack": "^5.73.0",
"webpack-cli": "^4.9.2", "webpack-cli": "^4.9.2",
"webpack-dev-server": "^4.9.1" "webpack-dev-server": "^4.9.1",
"webpack-merge": "^5.8.0"
} }
} }

View File

@ -16,6 +16,7 @@ import Register from '@pages/Register'
import FileDownload from '@pages/FileDownload' import FileDownload from '@pages/FileDownload'
import '@styles/App.less' import '@styles/App.less'
import '@styles/include/antd_theme.less'
//OpenAPI.BASE = 'http://localhost:3000' //OpenAPI.BASE = 'http://localhost:3000'
OpenAPI.TOKEN = async () => getUserToken() ?? '' OpenAPI.TOKEN = async () => getUserToken() ?? ''

View File

@ -1,18 +1,4 @@
@import '~antd/dist/antd.less';
@import './loader.css'; @import './loader.css';
/*
* ЭТО ФАЙЛ НАСТРОЙКИ ТЕМЫ И КОМПОНЕНТОВ ТЕМЫ.
* НЕ ПИШИТЕ ТУТ СТИЛИ ДЛЯ КАСТОМНЫХ КОМПОНЕНТОВ.
*/
// Переменные для темы тут:
// https://github.com/ant-design/ant-design/blob/master/components/style/themes/default.less
//@primary-color: rgba(124, 124, 124, 0.3);
@primary-color: rgb(195, 40,40);
//@primary-color:rgb(65, 63, 61);
//@layout-header-background: rgb(195, 40,40);
@layout-header-background: rgb(65, 63, 61);
@header-height: 64px; @header-height: 64px;
@layout-min-height: calc(100vh - @header-height); @layout-min-height: calc(100vh - @header-height);

View File

@ -0,0 +1,14 @@
@import '~antd/dist/antd.less';
/*
* ЭТО ФАЙЛ НАСТРОЙКИ ТЕМЫ И КОМПОНЕНТОВ ТЕМЫ.
* НЕ ПИШИТЕ ТУТ СТИЛИ ДЛЯ КАСТОМНЫХ КОМПОНЕНТОВ.
*/
// Переменные для темы тут:
// https://github.com/ant-design/ant-design/blob/master/components/style/themes/default.less
//@primary-color: rgba(124, 124, 124, 0.3);
@primary-color: rgb(195, 40,40);
//@primary-color:rgb(65, 63, 61);
//@layout-header-background: rgb(195, 40,40);
@layout-header-background: rgb(65, 63, 61);

106
webpack.config.base.js Normal file
View File

@ -0,0 +1,106 @@
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const InterpolateHtmlPlugin = require('interpolate-html-plugin')
const proxy = require('./package.json').proxy
module.exports = {
entry: './src/index.tsx',
output: {
path: path.resolve(__dirname, 'build'),
filename: '[name].[contenthash:8].js',
publicPath: '/',
},
devServer: {
historyApiFallback: true,
port: 3000,
proxy: {
context: ['/api', '/auth', '/hubs'],
target: proxy,
},
},
optimization: {
splitChunks: {
cacheGroups: {
commons: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all',
},
},
},
removeAvailableModules: true,
removeEmptyChunks: true,
mergeDuplicateChunks: true,
providedExports: true,
runtimeChunk: true,
},
resolve: {
fallback: { 'path': require.resolve('path-browserify') }, // TODO: Remove
modules: [path.join(__dirname, 'src'), 'node_modules'],
alias: {
react: path.join(__dirname, 'node_modules', 'react'),
'@asb': path.resolve(__dirname, 'src'),
'@api': path.resolve(__dirname, 'src/services/api'),
'@components': path.resolve(__dirname, 'src/components'),
'@services': path.resolve(__dirname, 'src/services'),
'@pages': path.resolve(__dirname, 'src/pages'),
'@utils': path.resolve(__dirname, 'src/utils'),
'@images': path.resolve(__dirname, 'src/images'),
'@styles': path.resolve(__dirname, 'src/styles'),
},
extensions: [ '', '.tsx', '.ts', '.jsx', '.js', '.json', '.d.ts', '.svg', '.png' ],
},
module: {
rules: [
{
test: /\.js$/,
enforce: 'pre',
use: [ 'source-map-loader' ],
},
{
test: /\.m?jsx?$/i,
exclude: /node_modules/,
use: [ 'babel-loader' ],
},
{
test: /\.m?tsx?$/i,
exclude: /node_modules/,
use: [ 'babel-loader', 'ts-loader' ],
},
{
test: /\.(jpe?g|gif|png)$/i,
use: [
{
loader: 'file-loader',
options: {
publicPath: '/images/',
outputPath: 'images',
name: '[name].[contenthash:8].[ext]',
},
},
],
},
{
test: /\.svg$/i,
issuer: /\.m?[jt]sx?$/,
use: [
'@svgr/webpack',
{
loader: 'file-loader',
options: {
publicPath: '/images/svg/',
outputPath: 'images/svg',
name: '[name].[contenthash:8].[ext]',
},
},
],
},
],
},
plugins: [
new InterpolateHtmlPlugin({ PUBLIC_URL: 'static' }),
new HtmlWebpackPlugin({ template: './public/index.html' }),
],
}

76
webpack.config.dev.js Normal file
View File

@ -0,0 +1,76 @@
const { HotModuleReplacementPlugin, SourceMapDevToolPlugin } = require('webpack')
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const TerserPlugin = require('terser-webpack-plugin')
const path = require('path')
const lessLoader = {
loader: 'less-loader',
options: {
lessOptions: {
javascriptEnabled: true,
},
},
}
module.exports = {
cache: true,
performance: false,
mode: 'development',
devtool: 'source-map',
optimization: {
minimizer: [
new CssMinimizerPlugin(),
new TerserPlugin(),
],
flagIncludedChunks: false,
usedExports: false,
sideEffects: false,
concatenateModules: false,
emitOnErrors: true,
nodeEnv: 'development',
minimize: false,
},
output: {
path: path.resolve(__dirname, 'dev_build'),
pathinfo: true,
},
stats: 'errors-warnings',
module: {
unsafeCache: true,
rules: [
{
test: /\.css$/i,
use: [
MiniCssExtractPlugin.loader,
'css-loader'
],
},
{
test: /\.less$/i,
exclude: path.resolve(__dirname, 'src/styles/include/'),
use: [
MiniCssExtractPlugin.loader,
'css-loader',
lessLoader,
],
},
{
test: /\.less$/i,
include: path.resolve(__dirname, 'src/styles/include/'),
use: [
'style-loader',
'css-loader',
lessLoader,
]
},
]
},
plugins: [
new MiniCssExtractPlugin({
filename: '[name].[contenthash:8].css',
}),
new HotModuleReplacementPlugin(),
new SourceMapDevToolPlugin({ filename: 'maps/[file].map' }),
],
}

View File

@ -1,141 +1,55 @@
const { merge } = require('webpack-merge')
const process = require('process')
const colors = require('colors')
const path = require('path') const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin') const fs = require('fs')
const { HotModuleReplacementPlugin, SourceMapDevToolPlugin } = require('webpack')
const InterpolateHtmlPlugin = require('interpolate-html-plugin')
const proxy = require('./package.json').proxy colors.enable()
module.exports = { const baseConfigPath = path.resolve(__dirname, 'webpack.config.base.js')
entry: './src/index.tsx',
devtool: 'source-map',
output: {
path: path.resolve(__dirname, 'build'),
filename: '[name].[contenthash:8].js',
publicPath: '/',
},
optimization: {
splitChunks: {
cacheGroups: {
commons: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all',
},
},
},
},
resolve: {
fallback: { 'path': require.resolve('path-browserify') }, // TODO: Remove
modules: [path.join(__dirname, 'src'), 'node_modules'],
alias: {
react: path.join(__dirname, 'node_modules', 'react'),
'@asb': path.resolve(__dirname, 'src'), const quit = (error = false) => {
'@api': path.resolve(__dirname, 'src/services/api'), console.log('Exiting...')
'@components': path.resolve(__dirname, 'src/components'), process.exit(error ? 1 : 0)
'@services': path.resolve(__dirname, 'src/services'), }
'@pages': path.resolve(__dirname, 'src/pages'),
'@utils': path.resolve(__dirname, 'src/utils'), module.exports = (env) => {
'@images': path.resolve(__dirname, 'src/images'), if (!fs.existsSync(path.resolve(__dirname, 'src/services/api'))) {
'@styles': path.resolve(__dirname, 'src/styles'), console.error(`Error: Services not found! Generate it first!`.bold.red)
}, console.info('To generate services you can use node scripts.')
extensions: [ '', '.tsx', '.ts', '.jsx', '.js', '.json', '.d.ts', '.svg', '.png' ], console.info('For example: `npm run oug_dev` for generate services from dev-server.')
},
devServer: { console.error(`Ошибка: Сервисы не найдены! Сначала сгенерируйте их!`.bold.red)
historyApiFallback: true, console.info('Для генерации сервисов воспользуйтесь node-скриптами.')
port: 3000, console.info('Например: `npm run oug_dev` для генерации от dev-сервера.')
proxy: { quit(1)
context: ['/api', '/auth', '/hubs'], }
target: proxy,
}, if (!fs.existsSync(baseConfigPath)) {
}, console.error(`Error: Base webpack config file not found!`.bold.red)
stats: 'errors-warnings', console.error(`Ошибка: базовый конфигурационный файл webpack не найден!`.bold.red)
// { quit(1)
// colors: true, }
// hash: false,
// version: false, const mode = String(env.ENV)
// timings: false, const configPath = path.resolve(__dirname, `webpack.config.${env.ENV}.js`)
// assets: false,
// chunks: false, if (!fs.existsSync(configPath)) {
// modules: false, console.error(`Error: Webpack config file for mode "${mode.underline}" not found!`.bold.red)
// reasons: false, console.error(`Ошибка: конфигурационный файл webpack для режима "${mode.underline}" не найден!`.bold.red)
// children: false, quit(1)
// source: false, }
// errors: false,
// errorDetails: false, console.info('Make sure you update your npm packages and services!'.bold.yellow)
// warnings: false, console.info('Убедитесь, что вы обновили npm-пакеты и сервисы!'.bold.yellow)
// publicPath: false,
// }, console.info(`Building in mode: ${String(env.ENV).blue.bold}`)
module: { console.info(`Using base config: ${baseConfigPath.underline.italic}`)
rules: [ console.info(`Using main config: ${configPath.underline.italic}`)
{
test: /\.js$/, console.info(`Собрка в режиме: ${String(env.ENV).blue.bold}`)
enforce: 'pre', console.info(`Базовый конфигурационный файл: ${baseConfigPath.underline.italic}`)
use: [ 'source-map-loader' ], console.info(`Режимный конфигурационный файл: ${configPath.underline.italic}`)
},
{ return merge(require(baseConfigPath), require(configPath))
test: /\.m?jsx?$/i,
exclude: /node_modules/,
use: [ 'babel-loader' ],
},
{
test: /\.m?tsx?$/i,
exclude: /node_modules/,
use: [ 'babel-loader', 'ts-loader' ],
},
{
test: /\.css$/i,
use: [ 'style-loader', 'css-loader' ],
},
{
test: /\.less$/i,
use: [
'style-loader',
'css-loader',
{
loader: 'less-loader',
options: {
lessOptions: {
javascriptEnabled: true,
},
},
},
],
},
{
test: /\.(jpe?g|gif|png)$/i,
use: [
{
loader: 'file-loader',
options: {
publicPath: '/images/',
outputPath: 'images',
name: '[name].[contenthash:8].[ext]',
},
},
],
},
{
test: /\.svg$/i,
issuer: /\.m?[jt]sx?$/,
use: [
'@svgr/webpack',
{
loader: 'file-loader',
options: {
publicPath: '/images/svg/',
outputPath: 'images/svg',
name: '[name].[contenthash:8].[ext]',
},
},
],
},
],
},
plugins: [
new HotModuleReplacementPlugin(),
new InterpolateHtmlPlugin({ PUBLIC_URL: 'static' }),
new SourceMapDevToolPlugin({ filename: '[file].map' }),
new HtmlWebpackPlugin({ template: './public/index.html' }),
],
} }

58
webpack.config.prod.js Normal file
View File

@ -0,0 +1,58 @@
const path = require('path')
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin')
const TerserPlugin = require('terser-webpack-plugin')
module.exports = {
mode: 'production',
performance: {
assetFilter: (assetFilename) => !/\.map$/.test(assetFilename),
hints: 'error',
maxAssetSize: 300 * 1024, // 300KB
},
cache: false,
output: {
path: path.resolve(__dirname, 'prod_build'),
pathinfo: false,
},
optimization: {
minimizer: [
new CssMinimizerPlugin(),
new TerserPlugin(),
],
flagIncludedChunks: true,
usedExports: true,
sideEffects: true,
concatenateModules: true,
emitOnErrors: false,
nodeEnv: 'production',
minimize: true,
},
stats: 'errors-warnings',
module: {
unsafeCache: false,
rules: [
{
test: /\.css$/i,
use: [
'style-loader',
'css-loader'
],
},
{
test: /\.less$/i,
use: [
'style-loader',
'css-loader',
{
loader: 'less-loader',
options: {
lessOptions: {
javascriptEnabled: true,
},
},
},
],
}
]
},
}