PR-753737: Se agrega ESLint a webpack.

This commit is contained in:
Alejandro Lembke Barrientos 2022-04-20 00:21:16 +00:00
parent e87a638e7d
commit d6f2d2d5dd
20 changed files with 3164 additions and 295 deletions

7
src/.eslintignore Normal file
View File

@ -0,0 +1,7 @@
#Build
build
#Webpack
webpack.config.js
webpack.config.dev.js
#Server
/server/index.js

51
src/.eslintrc.js Normal file
View File

@ -0,0 +1,51 @@
module.exports = {
'env': {
'browser': true,
'node': true,
'es2021': true
},
'extends': [
'eslint:recommended',
'plugin:react/recommended',
'plugin:@typescript-eslint/recommended'
],
'parser': '@typescript-eslint/parser',
'parserOptions': {
'ecmaFeatures': {
'jsx': true
},
'ecmaVersion': 'latest',
'sourceType': 'module'
},
'plugins': [
'react',
'@typescript-eslint'
],
'rules': {
'indent': [
'error',
'tab'
],
'linebreak-style': [
'error',
'unix'
],
'quotes': [
'error',
'single'
],
'semi': [
'error',
'always'
],
'eol-last': [
'error',
'always'
]
},
'settings': {
'react': {
'version': 'detect',
}
}
};

View File

@ -1,11 +1,11 @@
const PRName = function () { const PRName = function () {
let ID = ""; let ID = '';
// let characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; // let characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
let characters = "0123456789"; const characters = '0123456789';
for ( var i = 0; i < 6; i++ ) { for ( let i = 0; i < 6; i++ ) {
ID += characters.charAt(Math.floor(Math.random() * 10)); ID += characters.charAt(Math.floor(Math.random() * 10));
} }
return 'PR-'+ID; return 'PR-'+ID;
}; };
console.log(PRName()) console.log(PRName());

View File

@ -1,8 +1,8 @@
const config = { const config = {
env: process.env.ENV ? process.env.ENV : 'production', env: process.env.ENV ? process.env.ENV : 'production',
port: process.env.PORT ? process.env.PORT : 80, port: process.env.PORT ? process.env.PORT : 80,
// portDev: process.env.PORT_DEV ? process.env.PORT_DEV : 3000, // portDev: process.env.PORT_DEV ? process.env.PORT_DEV : 3000,
// portReloadDev: process.env.PORT_RELOAD_DEV, // portReloadDev: process.env.PORT_RELOAD_DEV,
} };
module.exports = { config: config }; module.exports = { config: config };

View File

@ -1,6 +1,6 @@
import React from 'react'; import React from 'react';
import PrincipalRoutes from './PrincipalRoutes'; import PrincipalRoutes from './PrincipalRoutes';
const App = () => <PrincipalRoutes /> const App = () => <PrincipalRoutes />;
export default App; export default App;

View File

@ -1,5 +1,5 @@
import React from 'react'; import React from 'react';
const InitialComponent = () => <h1>Hello React!</h1> const InitialComponent = () => <h1>Hello React!</h1>;
export default InitialComponent; export default InitialComponent;

View File

@ -1,5 +1,5 @@
import React from 'react'; import React from 'react';
const OtherComponent = () => <h1>Other Component!</h1> const OtherComponent = () => <h1>Other Component!</h1>;
export default OtherComponent; export default OtherComponent;

View File

@ -4,8 +4,8 @@ import { useRoutes } from 'react-router-dom';
import routes from '../../routes'; import routes from '../../routes';
const PrincipalRoutes = () => { const PrincipalRoutes = () => {
let element = useRoutes(routes); let element = useRoutes(routes);
return element return element;
} };
export default PrincipalRoutes; export default PrincipalRoutes;

View File

@ -1,10 +1,10 @@
import React from 'react'; import React from 'react';
import { hydrateRoot } from 'react-dom/client'; import { hydrateRoot } from 'react-dom/client';
//Router // Router
import { BrowserRouter as Router } from 'react-router-dom'; import { BrowserRouter as Router } from 'react-router-dom';
//History // History
import { createBrowserHistory } from 'history'; import { createBrowserHistory } from 'history';
//Redux // Redux
import { createStore } from 'redux'; //, applyMiddleware import { createStore } from 'redux'; //, applyMiddleware
import { Provider } from 'react-redux'; import { Provider } from 'react-redux';
import { composeWithDevTools as composeWithDevToolsWeb } from 'redux-devtools-extension'; import { composeWithDevTools as composeWithDevToolsWeb } from 'redux-devtools-extension';
@ -14,43 +14,44 @@ import reducer from './reducers';
import App from './components/App'; import App from './components/App';
import './styles/global.sass'; import './styles/global.sass';
//Redux DevTools // Redux DevTools
/* declare global { /* declare global {
interface Window { interface Window {
__REDUX_DEVTOOLS_EXTENSION_COMPOSE__?: typeof compose; __REDUX_DEVTOOLS_EXTENSION_COMPOSE__?: typeof compose;
} }
} */ } */
const { env } = config const { env } = config;
const composeEnhancers = composeWithDevToolsWeb({ const composeEnhancers = composeWithDevToolsWeb({
// Specify here name, actionsBlacklist, actionsCreators and other options // Specify here name, actionsBlacklist, actionsCreators and other options
}); });
const preloadedState = window.__PRELOADED_STATE__ const preloadedState = window.__PRELOADED_STATE__;
const store = env === 'development' ? createStore( const store = env === 'development' ? createStore(
reducer, reducer,
preloadedState, preloadedState,
composeEnhancers(), composeEnhancers(),
) : createStore( ) : createStore(
reducer, reducer,
preloadedState, preloadedState,
) );
delete window.__PRELOADED_STATE__ delete window.__PRELOADED_STATE__;
const container = document.getElementById('app'); const container = document.getElementById('app');
const history = createBrowserHistory() const history = createBrowserHistory();
const root = hydrateRoot(container, // add "const root" to be able to rerender.
<Provider store={store}> hydrateRoot(container,
<Router history={history}> <Provider store={store}>
<App /> <Router history={history}>
</Router> <App />
</Provider>, </Router>
//Add this comment to update later app and remove warning </Provider>,
/*{ // Add this comment to update later app and remove warning
/* {
onRecoverableError: (error) => { onRecoverableError: (error) => {
console.error("recoverable", error); console.error("recoverable", error);
} }
@ -67,5 +68,5 @@ const root = hydrateRoot(container,
); */ ); */
if (module.hot) { if (module.hot) {
module.hot.accept(); module.hot.accept();
} }

View File

@ -2,8 +2,8 @@ import { combineReducers } from 'redux';
import testReducer from './testReducer'; import testReducer from './testReducer';
const rootReducer = combineReducers({ const rootReducer = combineReducers({
//Here comes the reducers // Here comes the reducers
testReducer testReducer
}) });
export default rootReducer export default rootReducer;

View File

@ -1,3 +1,3 @@
let initialState = {} let initialState = {};
export default initialState export default initialState;

View File

@ -1,18 +1,18 @@
const initialState = { const initialState = {
hello: 'world' hello: 'world'
} };
let testReducer = (state = initialState, action) => { let testReducer = (state = initialState, action) => {
switch (action.type){ switch (action.type){
case 'CHANGE_HELLO': { case 'CHANGE_HELLO': {
let newHello = action.payload.hello let newHello = action.payload.hello;
return { return {
hello: newHello hello: newHello
} };
} }
default: default:
return state return state;
} }
} };
export default testReducer export default testReducer;

2799
src/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -6,6 +6,8 @@
"scripts": { "scripts": {
"start": "nodemon server/index", "start": "nodemon server/index",
"build": "webpack-cli --config webpack.config.js", "build": "webpack-cli --config webpack.config.js",
"lint": "eslint ./ --ext .js --ext .ts --ext .jsx --ext .tsx",
"lint:fix": "eslint ./ --ext .js --ext .ts --ext .jsx --ext .tsx --fix",
"test": "echo \"Error: no test specified\" && exit 1" "test": "echo \"Error: no test specified\" && exit 1"
}, },
"repository": { "repository": {
@ -44,11 +46,16 @@
"@babel/preset-env": "^7.16.11", "@babel/preset-env": "^7.16.11",
"@babel/preset-react": "^7.16.7", "@babel/preset-react": "^7.16.7",
"@pmmmwh/react-refresh-webpack-plugin": "^0.5.5", "@pmmmwh/react-refresh-webpack-plugin": "^0.5.5",
"@typescript-eslint/eslint-plugin": "^5.20.0",
"@typescript-eslint/parser": "^5.20.0",
"babel-loader": "^8.2.4", "babel-loader": "^8.2.4",
"clean-webpack-plugin": "^4.0.0", "clean-webpack-plugin": "^4.0.0",
"compression-webpack-plugin": "^9.2.0", "compression-webpack-plugin": "^9.2.0",
"css-loader": "^6.7.1", "css-loader": "^6.7.1",
"css-minimizer-webpack-plugin": "^3.4.1", "css-minimizer-webpack-plugin": "^3.4.1",
"eslint": "^8.13.0",
"eslint-plugin-react": "^7.29.4",
"eslint-webpack-plugin": "^3.1.1",
"mini-css-extract-plugin": "^2.6.0", "mini-css-extract-plugin": "^2.6.0",
"nodemon": "^2.0.15", "nodemon": "^2.0.15",
"react-refresh": "^0.12.0", "react-refresh": "^0.12.0",

View File

@ -1,16 +1,16 @@
import React from "react"; import React from 'react';
import InitialComponent from "../frontend/components/InitialComponent"; import InitialComponent from '../frontend/components/InitialComponent';
import OtherComponent from "../frontend/components/OtherComponent"; import OtherComponent from '../frontend/components/OtherComponent';
const OTHER_COMPONENT = { const OTHER_COMPONENT = {
path: 'other-component', path: 'other-component',
element: <OtherComponent /> element: <OtherComponent />
} };
const INITIAL_COMPONENT = { const INITIAL_COMPONENT = {
path: '/', path: '/',
element: <InitialComponent />, element: <InitialComponent />,
} };
export default [ INITIAL_COMPONENT, OTHER_COMPONENT ] export default [ INITIAL_COMPONENT, OTHER_COMPONENT ];

View File

@ -1,11 +1,11 @@
import fs from 'fs'; import fs from 'fs';
const getHashManifest = () => { const getHashManifest = () => {
try { try {
return JSON.parse(fs.readFileSync(`${__dirname}/../build/assets/manifest-hash.json`)) return JSON.parse(fs.readFileSync(`${__dirname}/../build/assets/manifest-hash.json`));
}catch(err){ }catch(err){
console.error(err) console.error(err);
} }
} };
export default getHashManifest export default getHashManifest;

View File

@ -3,30 +3,30 @@ require('dotenv').config();
require('ignore-styles'); require('ignore-styles');
require('@babel/register')({ require('@babel/register')({
"presets": [ 'presets': [
"@babel/preset-env", '@babel/preset-env',
"@babel/preset-react" '@babel/preset-react'
] ]
}); });
require('asset-require-hook')({ require('asset-require-hook')({
extensions: [ extensions: [
//images // images
'jpg', 'jpg',
'png', 'png',
'svg', 'svg',
'gif', 'gif',
//videos // videos
'mp4', 'mp4',
'avi', 'avi',
//typography // typography
'ttf', 'ttf',
'otf', 'otf',
'eot', 'eot',
//files // files
'pdf' 'pdf'
], ],
name: '/assets/[hash].[ext]', name: '/assets/[hash].[ext]',
}); });
require('./server'); require('./server');

View File

@ -13,7 +13,7 @@ import webpackHotMiddleware from 'webpack-hot-middleware';
import React from 'react'; import React from 'react';
import { renderToString } from 'react-dom/server'; import { renderToString } from 'react-dom/server';
//Router //Router
import { StaticRouter } from "react-router-dom/server"; import { StaticRouter } from 'react-router-dom/server';
//Redux //Redux
import { createStore } from 'redux'; //, applyMiddleware import { createStore } from 'redux'; //, applyMiddleware
import { Provider } from 'react-redux'; import { Provider } from 'react-redux';
@ -24,49 +24,49 @@ import getHashManifest from './getHashManifest';
//App //App
import App from '../frontend/components/App'; import App from '../frontend/components/App';
const { env, port } = config const { env, port } = config;
const app = express(); const app = express();
if(env === 'development'){ if(env === 'development'){
const compiler = webpack(webpackConfig); const compiler = webpack(webpackConfig);
const serverConfig = { const serverConfig = {
serverSideRender: true, serverSideRender: true,
publicPath: webpackConfig.output.publicPath, publicPath: webpackConfig.output.publicPath,
}; };
app app
.use(webpackDevMiddleware(compiler, serverConfig)) .use(webpackDevMiddleware(compiler, serverConfig))
.use(webpackHotMiddleware(compiler, { .use(webpackHotMiddleware(compiler, {
path: "/reload_wss", path: '/reload_wss',
heartbeat: 1000, heartbeat: 1000,
})); }));
}else{ }else{
app app
.use((req, res, next) => { .use((req, res, next) => {
if(!req.hashManifest) req.hashManifest = getHashManifest(); if(!req.hashManifest) req.hashManifest = getHashManifest();
next(); next();
}) })
.use(express.static(`${__dirname}/../build`)) .use(express.static(`${__dirname}/../build`))
.use(helmet()) .use(helmet())
.use(helmet.permittedCrossDomainPolicies()) .use(helmet.permittedCrossDomainPolicies())
.use(helmet({ .use(helmet({
contentSecurityPolicy: { contentSecurityPolicy: {
directives: { directives: {
...helmet.contentSecurityPolicy.getDefaultDirectives(), ...helmet.contentSecurityPolicy.getDefaultDirectives(),
"script-src": ["'self'", "'unsafe-inline'"],//"example.com" 'script-src': ['\'self\'', '\'unsafe-inline\''],//"example.com"
}, },
}, },
})) }))
.disable('x-powered-by'); .disable('x-powered-by');
} }
const setResponse = (html, preloadedState, manifest) => { const setResponse = (html, preloadedState, manifest) => {
const mainStyles = manifest ? manifest['main.css'] : 'assets/app.css'; const mainStyles = manifest ? manifest['main.css'] : 'assets/app.css';
const mainBuild = manifest ? manifest['main.js'] : 'assets/app.js'; const mainBuild = manifest ? manifest['main.js'] : 'assets/app.js';
const vendorBuild = manifest ? manifest['vendors.js'] : 'assets/vendor.js'; const vendorBuild = manifest ? manifest['vendors.js'] : 'assets/vendor.js';
return(` return(`
<!DOCTYPE html> <!DOCTYPE html>
<html lang="es"> <html lang="es">
<head> <head>
@ -85,25 +85,25 @@ const setResponse = (html, preloadedState, manifest) => {
<script src="${vendorBuild}" type="text/javascript"></script> <script src="${vendorBuild}" type="text/javascript"></script>
</body> </body>
</html> </html>
`) `);
}
const renderApp = (req, res) => {
const store = createStore(reducer, initialState)
const preloadedState = store.getState();
const html = renderToString(
<Provider store={store}>
<StaticRouter location={req.url}>
<App />
</StaticRouter>
</Provider>
)
res.send(setResponse(html, preloadedState, req.hashManifest));
}; };
app.get('*', renderApp) const renderApp = (req, res) => {
const store = createStore(reducer, initialState);
const preloadedState = store.getState();
const html = renderToString(
<Provider store={store}>
<StaticRouter location={req.url}>
<App />
</StaticRouter>
</Provider>
);
res.send(setResponse(html, preloadedState, req.hashManifest));
};
app.get('*', renderApp);
app.listen(port, (err) => { app.listen(port, (err) => {
if(err) console.error(err) if(err) console.error(err);
else console.log(`Server running on port ${port}`); else console.log(`Server running on port ${port}`);
}); });

View File

@ -3,68 +3,70 @@ const dotenv = require('dotenv').config();
const webpack = require('webpack'); const webpack = require('webpack');
const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin'); const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin');
const ESLintPlugin = require('eslint-webpack-plugin');
module.exports = { module.exports = {
entry: ['webpack-hot-middleware/client?path=/reload_wss&timeout=2000&overlay=false&reload=true', './frontend/index.js'], entry: ['webpack-hot-middleware/client?path=/reload_wss&timeout=2000&overlay=false&reload=true', './frontend/index.js'],
output: { output: {
path: path.resolve(__dirname, 'build'), path: path.resolve(__dirname, 'build'),
filename: 'assets/app.js', filename: 'assets/app.js',
}, },
resolve: { resolve: {
extensions: ['.js', '.jsx'], extensions: ['.js', '.jsx'],
alias: { alias: {
'@components': path.resolve(__dirname, 'frontend/components/'), '@components': path.resolve(__dirname, 'frontend/components/'),
'@styles': path.resolve(__dirname, 'frontend/styles/'), '@styles': path.resolve(__dirname, 'frontend/styles/'),
} }
}, },
mode: 'development', mode: 'development',
module: { module: {
rules: [ rules: [
{ {
test: /\.(js|jsx|tsx)$/, test: /\.(js|jsx|tsx)$/,
exclude: /node_modules/, exclude: /node_modules/,
use: { use: {
loader: 'babel-loader', loader: 'babel-loader',
options: { plugins: ['react-refresh/babel'] } options: { plugins: ['react-refresh/babel'] }
}, },
}, },
{ {
test: /\.(css|sass|scss)$/, test: /\.(css|sass|scss)$/,
use: [ use: [
MiniCssExtractPlugin.loader, MiniCssExtractPlugin.loader,
'css-loader', 'css-loader',
'sass-loader', 'sass-loader',
], ],
}, },
] ]
}, },
plugins: [ plugins: [
new webpack.HotModuleReplacementPlugin(), new webpack.HotModuleReplacementPlugin(),
new ReactRefreshWebpackPlugin(), new ReactRefreshWebpackPlugin(),
new MiniCssExtractPlugin({ new MiniCssExtractPlugin({
filename: 'assets/app.css', filename: 'assets/app.css',
}), }),
new webpack.DefinePlugin({ new ESLintPlugin(),
'process.env': JSON.stringify(dotenv.parsed), new webpack.DefinePlugin({
}), 'process.env': JSON.stringify(dotenv.parsed),
], }),
optimization: { ],
splitChunks: { optimization: {
chunks: 'async', splitChunks: {
cacheGroups: { chunks: 'async',
vendors: { cacheGroups: {
name: 'vendors', vendors: {
chunks: 'all', name: 'vendors',
reuseExistingChunk: true, chunks: 'all',
priority: 1, reuseExistingChunk: true,
filename: 'assets/vendor.js', priority: 1,
enforce: true, filename: 'assets/vendor.js',
test (module, chunks){ enforce: true,
const name = module.nameForCondition && module.nameForCondition(); test (module, chunks){
return chunks.name !== 'vendors' && /[\\/]node_modules[\\/]/.test(name); const name = module.nameForCondition && module.nameForCondition();
}, return chunks.name !== 'vendors' && /[\\/]node_modules[\\/]/.test(name);
}, },
}, },
}, },
}, },
} },
};

View File

@ -7,79 +7,81 @@ const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin'); const TerserPlugin = require('terser-webpack-plugin');
const { WebpackManifestPlugin } = require('webpack-manifest-plugin'); const { WebpackManifestPlugin } = require('webpack-manifest-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin'); const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const ESLintPlugin = require('eslint-webpack-plugin');
module.exports = { module.exports = {
entry: './frontend/index.js', entry: './frontend/index.js',
output: { output: {
path: path.resolve(__dirname, 'build'), path: path.resolve(__dirname, 'build'),
filename: 'assets/app-[fullhash].js', filename: 'assets/app-[fullhash].js',
publicPath: '/', publicPath: '/',
}, },
resolve: { resolve: {
extensions: ['.js', '.jsx'], extensions: ['.js', '.jsx'],
alias: { alias: {
'@components': path.resolve(__dirname, 'frontend/components/'), '@components': path.resolve(__dirname, 'frontend/components/'),
'@styles': path.resolve(__dirname, 'frontend/styles/'), '@styles': path.resolve(__dirname, 'frontend/styles/'),
} }
}, },
mode: 'production', mode: 'production',
module: { module: {
rules: [ rules: [
{ {
test: /\.(js|jsx|tsx)$/, test: /\.(js|jsx|tsx)$/,
exclude: /node_modules/, exclude: /node_modules/,
use: { use: {
loader: 'babel-loader', loader: 'babel-loader',
}, },
}, },
{ {
test: /\.(css|sass|scss)$/, test: /\.(css|sass|scss)$/,
use: [ use: [
MiniCssExtractPlugin.loader, MiniCssExtractPlugin.loader,
'css-loader', 'css-loader',
'sass-loader', 'sass-loader',
], ],
}, },
], ],
}, },
plugins: [ plugins: [
new CompressionWebpackPlugin({ new CompressionWebpackPlugin({
test: /\.(js|css)$/, test: /\.(js|css)$/,
filename: '[path][base].gz', filename: '[path][base].gz',
}), }),
new MiniCssExtractPlugin({ new MiniCssExtractPlugin({
filename: 'assets/app-[fullhash].css', filename: 'assets/app-[fullhash].css',
}), }),
new WebpackManifestPlugin({ new WebpackManifestPlugin({
fileName: 'assets/manifest-hash.json', fileName: 'assets/manifest-hash.json',
}), }),
new CleanWebpackPlugin(), new CleanWebpackPlugin(),
new webpack.DefinePlugin({ new ESLintPlugin(),
'process.env': JSON.stringify(dotenv.parsed), new webpack.DefinePlugin({
}), 'process.env': JSON.stringify(dotenv.parsed),
], }),
optimization: { ],
minimize: true, optimization: {
minimizer: [ minimize: true,
new CssMinimizerPlugin(), minimizer: [
new TerserPlugin(), new CssMinimizerPlugin(),
], new TerserPlugin(),
splitChunks: { ],
chunks: 'async', splitChunks: {
cacheGroups: { chunks: 'async',
vendors: { cacheGroups: {
name: 'vendors', vendors: {
chunks: 'all', name: 'vendors',
reuseExistingChunk: true, chunks: 'all',
priority: 1, reuseExistingChunk: true,
filename: 'assets/vendor-[fullhash].js', priority: 1,
enforce: true, filename: 'assets/vendor-[fullhash].js',
test (module, chunks){ enforce: true,
const name = module.nameForCondition && module.nameForCondition(); test (module, chunks){
return chunks.name !== 'vendors' && /[\\/]node_modules[\\/]/.test(name); const name = module.nameForCondition && module.nameForCondition();
}, return chunks.name !== 'vendors' && /[\\/]node_modules[\\/]/.test(name);
}, },
}, },
}, },
}, },
} },
};