initial commit

This commit is contained in:
Corey 2019-05-19 08:48:03 -04:00
commit 6c200e82ed
26 changed files with 893 additions and 0 deletions

2
.browserslistrc Normal file
View File

@ -0,0 +1,2 @@
> 0.25%
not dead

77
.eslintrc Normal file
View File

@ -0,0 +1,77 @@
{
"parser": "babel-eslint",
"plugins": ["react", "jest", "prettier"],
"extends": ["airbnb", "plugin:prettier/recommended", "prettier/react"],
"globals": {
"React": true,
"document": true,
"window": true,
"jQuery": true,
"$": true,
"localStorage": true,
"fetch": true
},
"root": true,
"rules": {
"indent": ["error", 2],
"react/prefer-stateless-function": "warn",
"react/self-closing-comp": [
"warn",
{
"component": true,
"html": false
}
],
"react/sort-comp": [
1,
{
"order": [
"static-methods",
"lifecycle",
"everything-else",
"rendering"
],
"groups": {
"rendering": ["/^render.+$/", "render"]
}
}
],
"jest/no-disabled-tests": "warn",
"jest/no-focused-tests": "error",
"jest/no-identical-title": "error",
"jest/prefer-to-have-length": "warn",
"jest/valid-expect": "error",
"react/require-default-props": 0,
"jsx-a11y/href-no-hash": "off",
"jsx-a11y/anchor-is-valid": ["warn", { "aspects": ["invalidHref"] }],
"react/jsx-boolean-value": ["warn", "never"],
"react/jsx-closing-bracket-location": ["warn", "after-props"],
"react/jsx-curly-spacing": ["warn", "never"],
"react/jsx-filename-extension": ["warn", { "extensions": [".jsx"] }],
"react/jsx-first-prop-new-line": ["warn", "multiline"],
"react/jsx-handler-names": [
"warn",
{
"eventHandlerPrefix": "handle",
"eventHandlerPropPrefix": "on"
}
],
"react/jsx-indent": ["warn", 2],
"react/jsx-key": "error",
"react/jsx-wrap-multilines": ["warn"],
"react/jsx-indent-props": 0,
"no-trailing-spaces": [2, { "skipBlankLines": true }],
"prefer-template": 0,
"import/prefer-default-export": 0,
"import/no-unresolved": 0,
"import/no-extraneous-dependencies": 0,
"import/extensions": 0,
"babel/object-curly-spacing": 0
},
"env": {
"es6": true,
"jest": true,
"browser": true,
"node": true
}
}

29
.gitignore vendored Normal file
View File

@ -0,0 +1,29 @@
# Cruft
*~
*#
.#*
.DS_Store
# Test
coverage
.eslintcache
# Logs
*.log
# npm & yarn
node_modules/
.npm
.yarn-integrity
npm-debug.log*
yarn-debug.log*
yarn-error.log*
yarn.lock*
package-lock.json
/build/bundle.js
/build/index.html
/build*
/build/*
# Editor/IDE
.idea
packages/api/etc/

4
.prettierrc Normal file
View File

@ -0,0 +1,4 @@
{
"singleQuote": true,
"trailingComma": "all"
}

46
CODE_OF_CONDUCT.md Normal file
View File

@ -0,0 +1,46 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at hashem.khalifa@gmail.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/

1
CONTRIBUTING.md Normal file
View File

@ -0,0 +1 @@

21
LICENSE Normal file
View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2018 Hashem Khalifa
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

1
__mocks__/fileMock.js Normal file
View File

@ -0,0 +1 @@
export default '';

3
__mocks__/styleMock.js Normal file
View File

@ -0,0 +1,3 @@
import idObj from 'identity-obj-proxy';
export default idObj;

17
__tests__/app.test.jsx Normal file
View File

@ -0,0 +1,17 @@
import React from 'react';
import { mount } from 'enzyme';
import App from '../src/App';
import HelloWorld from '../src/components/hello-world';
describe('<App />', () => {
const wrap = mount(<App />);
it('renders', () => {
expect(wrap.find(App).exists()).toBe(true);
});
it('contains HelloWorld component', () => {
expect(wrap.find(HelloWorld).exists()).toBe(true);
});
});

42
babel.config.js Normal file
View File

@ -0,0 +1,42 @@
module.exports = function(api) {
api.cache(true);
const presets = [
[
'@babel/preset-env',
{
targets: {
esmodules: true,
},
useBuiltIns: 'usage',
},
],
'@babel/preset-react',
];
const plugins = [
'@babel/transform-react-constant-elements',
'@babel/transform-react-inline-elements',
'transform-react-remove-prop-types',
'transform-react-pure-class-to-function',
'@babel/plugin-transform-runtime',
'react-hot-loader/babel',
// Stage 2 https://github.com/babel/babel/tree/master/packages/babel-preset-stage-2
['@babel/plugin-proposal-decorators', { legacy: true }],
'@babel/plugin-proposal-function-sent',
'@babel/plugin-proposal-export-namespace-from',
'@babel/plugin-proposal-numeric-separator',
'@babel/plugin-proposal-throw-expressions',
// Stage 3
'@babel/plugin-syntax-dynamic-import',
'@babel/plugin-syntax-import-meta',
['@babel/plugin-proposal-class-properties', { loose: true }],
'@babel/plugin-proposal-json-strings',
];
return {
presets,
plugins,
};
};

135
package.json Normal file
View File

@ -0,0 +1,135 @@
{
"name": "minimal-webpack-react",
"version": "2.0.0",
"description": "Boilerplate for react and webpack",
"main": "index.js",
"scripts": {
"start": "cross-env NODE_ENV=development webpack-dev-server --open",
"build": "cross-env NODE_ENV=production webpack",
"format": "prettier --write 'packages/**/*.js'",
"test": "jest --watchAll --coverage",
"precommit": "lint-staged"
},
"lint-staged": {
"*.{js,jsx,css,md}": [
"prettier --write --single-quote",
"eslint --fix",
"git add"
]
},
"jest": {
"testEnvironment": "jsdom",
"moduleDirectories": [
"src",
"node_modules"
],
"moduleNameMapper": {
"\\.(css|scss)$": "<rootDir>/__mocks__/styleMock.js",
"\\.(jpg|gif|ttf|eot|svg)$": "<rootDir>/__mocks__/fileMock.js"
},
"transform": {
"^.+\\.(js|jsx)$": "babel-jest",
".+\\.(css|styl|less|sass|scss)$": "<rootDir>/node_modules/jest-css-modules-transform"
},
"setupTestFrameworkScriptFile": "<rootDir>/setupTests.js",
"moduleFileExtensions": [
"css",
"scss",
"js",
"json",
"jsx"
]
},
"repository": "https://github.com/HashemKhalifa/webpack-react-boilerplate",
"author": "HashemKhalifa",
"license": "ISC",
"private": false,
"engines": {
"node": ">=8",
"npm": ">=3"
},
"dependencies": {
"@babel/plugin-transform-react-constant-elements": "7.2.0",
"@babel/plugin-transform-react-inline-elements": "7.2.0",
"@corpetty/test-graph-embed": "https://api.observablehq.com/@corpetty/test-graph-embed.tgz?v=3",
"@observablehq/runtime": "4",
"babel-plugin-transform-react-pure-class-to-function": "1.0.1",
"babel-plugin-transform-react-remove-prop-types": "0.4.24",
"lodash": "4.17.11",
"prop-types": "15.7.2",
"react": "16.8.6",
"react-dom": "16.8.6",
"react-hot-loader": "4.8.4",
"react-latex": "^1.2.0"
},
"resolutions": {
"babel-core": "7.0.0-bridge.0"
},
"devDependencies": {
"@babel/core": "7.4.4",
"@babel/plugin-proposal-class-properties": "7.4.4",
"@babel/plugin-proposal-decorators": "7.4.4",
"@babel/plugin-proposal-export-namespace-from": "7.2.0",
"@babel/plugin-proposal-function-sent": "7.2.0",
"@babel/plugin-proposal-json-strings": "7.2.0",
"@babel/plugin-proposal-numeric-separator": "7.2.0",
"@babel/plugin-proposal-throw-expressions": "7.2.0",
"@babel/plugin-syntax-dynamic-import": "7.2.0",
"@babel/plugin-syntax-import-meta": "7.2.0",
"@babel/plugin-transform-runtime": "7.4.4",
"@babel/polyfill": "7.4.4",
"@babel/preset-env": "7.4.4",
"@babel/preset-react": "7.0.0",
"@babel/register": "7.4.4",
"@babel/runtime": "7.4.4",
"babel-core": "7.0.0-bridge.0",
"babel-eslint": "10.0.1",
"babel-jest": "24.8.0",
"babel-loader": "8.0.6",
"babel-plugin-lodash": "3.3.4",
"babel-preset-react-optimize": "1.0.1",
"browserslist": "4.6.0",
"clean-webpack-plugin": "2.0.2",
"connect-history-api-fallback": "1.6.0",
"cross-env": "5.2.0",
"css-loader": "2.1.1",
"enzyme": "3.9.0",
"enzyme-adapter-react-16": "1.13.0",
"eslint": "5.16.0",
"eslint-config-airbnb": "17.1.0",
"eslint-config-prettier": "4.2.0",
"eslint-loader": "2.1.2",
"eslint-plugin-import": "2.17.2",
"eslint-plugin-jest": "22.5.1",
"eslint-plugin-jsx-a11y": "6.2.1",
"eslint-plugin-prettier": "3.1.0",
"eslint-plugin-react": "7.13.0",
"eslint-watch": "5.1.2",
"file-loader": "3.0.1",
"html-webpack-inline-source-plugin": "^0.0.10",
"html-webpack-plugin": "^3.2.0",
"husky": "2.2.0",
"identity-obj-proxy": "3.0.0",
"jest": "24.8.0",
"jest-css-modules-transform": "2.1.1",
"jest-enzyme": "7.0.2",
"jest-fetch-mock": "2.1.2",
"jsdom": "15.1.0",
"koa-connect": "2.0.1",
"lint-staged": "8.1.6",
"mini-css-extract-plugin": "0.6.0",
"node-sass": "4.12.0",
"npm-check-updates": "3.1.9",
"optimize-css-assets-webpack-plugin": "5.0.1",
"prettier": "1.17.1",
"pretty-quick": "1.10.0",
"sass-loader": "7.1.0",
"script-ext-html-webpack-plugin": "2.1.3",
"style-loader": "0.23.1",
"terser-webpack-plugin": "1.2.3",
"webpack": "4.31.0",
"webpack-cli": "3.3.2",
"webpack-dev-server": "3.3.1",
"webpack-merge": "4.2.1"
}
}

86
readme.md Normal file
View File

@ -0,0 +1,86 @@
## Webpack react minimal boilerplate
<p align="center">
<img alt="dependencies" title="dependencies" src="https://img.shields.io/david/hashemkhalifa/webpack-react-boilerplate.svg" >
<img alt="dependencies" title="dependencies" src="https://img.shields.io/github/last-commit/hashemkhalifa/webpack-react-boilerplate.svg" >
</p>
> Minimal webpack and react boilerplate using latest version of react and babel as well as jest and enzyme for more details about technologies used. [click](#technologies-used)
> with real time server changes ;)
> check out [Medium article](https://medium.com/@hashem.khalifa/minimal-webpack-and-react-starter-boilerplate-seriously-d90a673e134f) for more details
![Real time change](https://cdn-images-1.medium.com/max/1600/1*0Slpwk3trmF7kLeoFp5UOw.gif)
### Table of contents
[Project structure](#project-structure)
[Installation](#installation)
[Configuration](#configuration)
[Technologies used](#technologies-used)
### Project structure
````
build/
src/
|- index.jsx _______________________________ # Application entry
|- App.jsx _________________________________ # Application init
| |- Components/
| |- hello-world/
| |- index.jsx _______________________ # Sample component
webpack
|- paths.js ________________________________ # webpack paths needed
|- webpack.common.js _______________________ # common webpack config
|- webpack.dev.js __________________________ # development config
|- webpack.prod.js _________________________ # production config
````
### Installation
1- Clone the boilerplate repo
`git clone git@github.com:HashemKhalifa/webpack-react-boilerplate.git`
2- `yarn` or `npm install` to install npm packages
3- start dev server using `yarn start` or `npm start`.
3- build and bundling your resources for production `yarn build`.
4- Unit testing will watch all your changes in the test files as well as create coverage folder for you.
`yarn test`
### Configuration
* Webpack Config paths based on your file structure you can go to `webpack/paths.js` and modify the source and file names based on your need.
* `webpack/webpack.common.js` config common webpack for both dev and production environments.
* webpack/webpack.dev.js config webpack for dev environment.
* `webpack/webpack.prod.js` config webpack for production environment.
* `/webpack.config.js` main webpack config that merge common and webpack environment based config.
* Enzyme config `/setupTest.js` here you will have all setup for enzyme to test your component.
* Prettier config `/.prettierc`.
* Browsers list config `/.browserslistrc`.
#### Technologies used
* [Webpack 4](https://github.com/webpack/webpack)
* [Babel 7](https://github.com/babel/babel) [ transforming JSX and ES6,ES7,ES8 ]
* [React](https://github.com/facebook/react) `16.8`
* [Lodash](https://github.com/lodash/lodash)
* [Jest](https://github.com/facebook/jest) [ Unit test]
* [Enzyme](http://airbnb.io/enzyme/) for UI testing.
* [Eslint](https://github.com/eslint/eslint/) with airbnb config
* [Prettier](https://github.com/prettier/prettier) [ Code formatter ]
* [Style](https://github.com/webpack-contrib/style-loader) & [CSS Loader](https://github.com/webpack-contrib/css-loader) & [SASS-loader](https://github.com/webpack-contrib/sass-loader)
* [CSS modules](https://github.com/css-modules/css-modules) [ Isolated style based on each component ]
* [Browsers list](https://github.com/browserslist/browserslist) [ Share target browsers between different front-end tools, like Autoprefixer, Stylelint and babel-preset-env ]
* [React hot loader](https://github.com/gaearon/react-hot-loader)
* [Webpack dev serve](https://github.com/webpack/webpack-dev-server)

5
renovate.json Normal file
View File

@ -0,0 +1,5 @@
{
"extends": [
"config:base"
]
}

24
setupTests.js Executable file
View File

@ -0,0 +1,24 @@
import { JSDOM } from 'jsdom';
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
configure({ adapter: new Adapter() });
global.fetch = require('jest-fetch-mock');
const exposedProperties = ['window', 'navigator', 'document'];
const { document } = new JSDOM('').window;
global.document = document;
global.window = document.defaultView;
global.HTMLElement = window.HTMLElement;
global.HTMLAnchorElement = window.HTMLAnchorElement;
Object.keys(document.defaultView).forEach(property => {
if (typeof global[property] === 'undefined') {
exposedProperties.push(property);
global[property] = document.defaultView[property];
}
});
global.navigator = {
userAgent: 'node.js',
};

3
src/App.css Normal file
View File

@ -0,0 +1,3 @@
div {
/* max-width: 80% !important; */
}

142
src/App.jsx Normal file
View File

@ -0,0 +1,142 @@
import React, { Component } from 'react';
import { hot } from 'react-hot-loader/root';
import { Runtime, Inspector } from '@observablehq/runtime';
import notebook from '@corpetty/test-graph-embed';
import Latex from 'react-latex';
import style from './App.css';
class App extends Component {
componentDidMount() {
const runtime = new Runtime();
runtime.module(notebook, name => {
if (name === 'viewof numberStatusUsers') {
return new Inspector(this.numberUserInputRef.current);
}
if (name === 'viewof userGrowthRate') {
return new Inspector(this.userGrowthRateRef.current);
}
if (name === 'viewof userChurnRate') {
return new Inspector(this.userChurnRateRef.current);
}
if (name === 'viewof userbar') {
return new Inspector(this.userbarRef.current);
}
if (name === 'viewof percentUsersRegisterName') {
return new Inspector(this.userConversionRef.current);
}
if (name === 'viewof removalRate') {
return new Inspector(this.removalRateRef.current);
}
if (name === 'viewof ensUserbar') {
return new Inspector(this.ensUserbarRef.current);
}
if (name === 'viewof amountDepositSnt') {
return new Inspector(this.amountDepositSntRef.current);
}
if (name === 'viewof lockedSntBar') {
return new Inspector(this.lockedSntBarRef.current);
}
if (name === 'viewof sntPrice') {
return new Inspector(this.sntPriceRef.current);
}
if (name === 'viewof lockedUsdBar') {
return new Inspector(this.lockedUsdBarRef.current);
}
return null;
});
}
numberUserInputRef = React.createRef();
userGrowthRateRef = React.createRef();
userChurnRateRef = React.createRef();
userbarRef = React.createRef();
userConversionRef = React.createRef();
removalRateRef = React.createRef();
ensUserbarRef = React.createRef();
amountDepositSntRef = React.createRef();
lockedSntBarRef = React.createRef();
sntPriceRef = React.createRef();
lockedUsdBarRef = React.createRef();
render() {
return (
<div className="App">
<h2>Disucssion of variables</h2>
<h3>Number of Users</h3>
<p>
It is clear that this all depends on how many users Status has in the
app. If they are not using Status, then they wont use the feature.
This is our base metric, and we will model it using compounding growth
and loss. We can start with a number of users that are using the app,
and set additional growth and loss variables (in percentages) that
define how this number changes over the next 10 years. This means that
every year, we expect a certain percentage change in users based on
the numbers of the previous year. Depending on how you set those
percentages, the number of users can grow very rapidly! Go ahead and
play with the following variables to see how the number of users
change over the years.
</p>
<div ref={this.numberUserInputRef} />
<div ref={this.userGrowthRateRef} />
<div ref={this.userChurnRateRef} />
<div ref={this.userbarRef} className={style.chart} />
<h3>Conversion rate of users to ENS username</h3>
<p>
Ok cool. We have our user base locked and loaded for the next 10
years, but not everyone is going to register an ENS username. We can
brand it, make it simple, and incentivize people to do it but the
reality is that that number will never be 100%. So the number of
people that DO decide to register an ENS username is what we want. We
get this number by multiplying the total number of users by the
adoption conversion rate, which is another variable.
</p>
<p>
Now not all users will keep their usernames. Some people will remove
their deposit after the year and bring their SNT back into
circulation. Some people will leave Status altogether and [DESCRIBE
WHAT HAPPENS TO THIS SNT]. Well model this with another conversion
factor, which represents the number of people who renew their username
every year. Go ahead and change these variables and see how the
following graph changes
</p>
<div ref={this.userConversionRef} />
<div ref={this.removalRateRef} />
<div ref={this.ensUserbarRef} />
<h3>Amount of SNT to deposit and renewal time</h3>
<p>
Now we have the amount of users that have (or will) used this utility.
Lets figure out how that translates to SNT. In order to do that, we
have two more variables to define: The amount of SNT required to
register an ENS username, and the time this money is locked up. By
multiplying each user by these two variables, we can show how much SNT
is being locked up every year which effectively takes it out of the
circulating supply, i.e.
</p>
<h3>
<Latex displayMode>
{
'$$N_{\\text{SNT locked}} = N_{\\text{registrations}} * N_{\\text{amount per snt reg}}$$'
}
</Latex>
</h3>
<div ref={this.amountDepositSntRef} />
<div ref={this.lockedSntBarRef} />
<h3>How to assign value to all of this?</h3>
<div ref={this.sntPriceRef} />
<div ref={this.lockedUsdBarRef} />
</div>
);
}
}
export default hot(App);

View File

@ -0,0 +1,5 @@
.hello-world{
margin-top: 10rem;
font-size: 2rem;
text-align: center;
}

View File

@ -0,0 +1,13 @@
import React from 'react';
import PropTypes from 'prop-types';
import style from './hello-world.css';
const HelloWorld = ({ title }) => (
<div className={style['hello-world']}>{title}</div>
);
HelloWorld.propTypes = {
title: PropTypes.string,
};
export default HelloWorld;

5
src/index.jsx Normal file
View File

@ -0,0 +1,5 @@
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(<App />, document.getElementById('app'));

17
src/template.html Normal file
View File

@ -0,0 +1,17 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link href="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.9.0/katex.min.css" rel="stylesheet">
<title>Webpack react boilerplate</title>
</head>
<body>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<div id="app"></div>
</body>
</html>

11
webpack.config.js Normal file
View File

@ -0,0 +1,11 @@
const webpackMerge = require('webpack-merge');
const common = require('./webpack/webpack.common');
const envs = {
development: 'dev',
production: 'prod',
};
/* eslint-disable global-require,import/no-dynamic-require */
const env = envs[process.env.NODE_ENV || 'development'];
const envConfig = require(`./webpack/webpack.${env}.js`);
module.exports = webpackMerge(common, envConfig);

12
webpack/paths.js Normal file
View File

@ -0,0 +1,12 @@
const path = require('path');
module.exports = {
root: path.resolve(__dirname, '../'),
outputPath: path.resolve(__dirname, '../', 'build'),
entryPath: path.resolve(__dirname, '../', 'src/index.jsx'),
templatePath: path.resolve(__dirname, '../', 'src/template.html'),
imagesFolder: 'images',
fontsFolder: 'fonts',
cssFolder: 'css',
jsFolder: 'js',
};

76
webpack/webpack.common.js Normal file
View File

@ -0,0 +1,76 @@
const webpack = require('webpack');
const convert = require('koa-connect');
const history = require('connect-history-api-fallback');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const HtmlWebpackInlineSourcePlugin = require('html-webpack-inline-source-plugin');
const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin');
const commonPaths = require('./paths');
module.exports = {
entry: commonPaths.entryPath,
module: {
rules: [
{
enforce: 'pre',
test: /\.(js|jsx)$/,
loader: 'eslint-loader',
exclude: /(node_modules)/,
options: {
emitWarning: process.env.NODE_ENV !== 'production',
},
},
{
test: /\.(js|jsx)$/,
loader: 'babel-loader',
exclude: /(node_modules)/,
},
{
test: /\.(png|jpg|gif|svg)$/,
use: [
{
loader: 'file-loader',
options: {
outputPath: commonPaths.imagesFolder,
},
},
],
},
{
test: /\.(woff2|ttf|woff|eot)$/,
use: [
{
loader: 'file-loader',
options: {
outputPath: commonPaths.fontsFolder,
},
},
],
},
],
},
serve: {
add: app => {
app.use(convert(history()));
},
content: commonPaths.entryPath,
dev: {
publicPath: commonPaths.outputPath,
},
open: true,
},
resolve: {
modules: ['src', 'node_modules'],
extensions: ['*', '.js', '.jsx', '.css', '.scss'],
},
plugins: [
new webpack.ProgressPlugin(),
new HtmlWebpackPlugin({
template: commonPaths.templatePath,
inlineSource: '.(js|css)$' // embed all javascript and css inline
}),
new ScriptExtHtmlWebpackPlugin({
defaultAttribute: 'async',
}),
new HtmlWebpackInlineSourcePlugin(),
],
};

38
webpack/webpack.dev.js Normal file
View File

@ -0,0 +1,38 @@
const webpack = require('webpack');
const commonPaths = require('./paths');
module.exports = {
mode: 'development',
output: {
filename: '[name].js',
path: commonPaths.outputPath,
chunkFilename: '[name].js',
},
module: {
rules: [
{
test: /\.(css|scss)$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
sourceMap: true,
modules: true,
camelCase: true,
localIdentName: '[local]___[hash:base64:5]',
},
},
'sass-loader',
],
},
],
},
devServer: {
contentBase: commonPaths.outputPath,
compress: true,
hot: true,
},
plugins: [new webpack.HotModuleReplacementPlugin()],
};

78
webpack/webpack.prod.js Normal file
View File

@ -0,0 +1,78 @@
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const commonPaths = require('./paths');
module.exports = {
mode: 'production',
output: {
filename: `${commonPaths.jsFolder}/[name].[hash].js`,
path: commonPaths.outputPath,
chunkFilename: `${commonPaths.jsFolder}/[name].[chunkhash].js`,
},
optimization: {
minimizer: [
new TerserPlugin({
// Use multi-process parallel running to improve the build speed
// Default number of concurrent runs: os.cpus().length - 1
parallel: true,
// Enable file caching
cache: true,
sourceMap: true,
}),
new OptimizeCSSAssetsPlugin(),
],
// Automatically split vendor and commons
// https://twitter.com/wSokra/status/969633336732905474
// https://medium.com/webpack/webpack-4-code-splitting-chunk-graph-and-the-splitchunks-optimization-be739a861366
splitChunks: {
cacheGroups: {
vendors: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'initial',
},
async: {
test: /[\\/]node_modules[\\/]/,
name: 'async',
chunks: 'async',
minChunks: 4,
},
},
},
// Keep the runtime chunk seperated to enable long term caching
// https://twitter.com/wSokra/status/969679223278505985
runtimeChunk: true,
},
module: {
rules: [
{
test: /\.(css|scss)$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
options: {
sourceMap: false,
modules: true,
camelCase: true,
localIdentName: '[local]___[hash:base64:5]',
},
},
'sass-loader',
],
},
],
},
plugins: [
new CleanWebpackPlugin(),
new MiniCssExtractPlugin({
filename: `${commonPaths.cssFolder}/[name].css`,
chunkFilename: `${commonPaths.cssFolder}/[name].css`,
}),
],
devtool: 'source-map',
};