Skip to content

Instantly share code, notes, and snippets.

@mightyhorst
Last active November 8, 2019 01:57
Show Gist options
  • Select an option

  • Save mightyhorst/32958a1df2a2e5c1e5dcdbde5bab0136 to your computer and use it in GitHub Desktop.

Select an option

Save mightyhorst/32958a1df2a2e5c1e5dcdbde5bab0136 to your computer and use it in GitHub Desktop.
Webpack, Typescript and ReactJs
html{
display:block;
width:100vw;
height:100vh;
overflow:hidden;
padding: 0px;
margin: 0px;
}
body{
display:block;
width:100%;
height:100%;
overflow:hidden;
padding: 0px;
margin: 0px;
font-size: 12px;
-webpack-font-smoothing: antialiased;
font-family: 'helvetica neue', helvetica, arial, san-serif;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" integrity="sha256-NuCn4IvuZXdBaFKJOAcsU2Q3ZpwbdFisd5dux4jkQ5w=" crossorigin="anonymous" />
<link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Raleway" />
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" />
<title>
Playbook
</title>
</head>
<body>
<div id="root"></div>
</body>
</html>
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
/**
* @import Libraries
*/
/**
* @import Pages
*/
import HomePage from './pages/HomePage';
const renderApp = () => {
ReactDOM.render((
<div>
Hello World
</div>
),
document.getElementById('root')
);
}
const run = async () => {
renderApp();
}
run()
.catch()
{
"compilerOptions": {
"* @param: {string} outDir": "Redirect output structure to the directory.",
"outDir": "./dist/",
"* @param: {boolean} sourceMap": "Generates corresponding '.map' file. This is used in chrome debug tools to map any errors to the ts source rather than the compiled bundle which wouldnt be that helpful",
"sourceMap": true,
"* @param: {boolean} noImplicitAny": "Warn on expressions and declarations with an implied 'any' type.",
"noImplicitAny": false,
"* @param: {none|commonjs|amd|system|umd|es2015|esnext} module": "Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015' or 'esnext'.",
"module": "commonjs",
"* @param: {es3|es5|es6|es2015|es2016|es2017|es2018|es2019|es2020|esnext} target": "Specify ECMAScript target version. Permitted values are 'es3', 'es5', 'es6', 'es2015', 'es2016', 'es2017', 'es2018', 'es2019', 'es2020' or 'esnext'.",
"target": "es6",
"* @param: {preserve|react|react-native} jsx": "Specify JSX code generation: 'preserve', 'react', or 'react-native'.",
"jsx": "react",
"* @param: {boolean} esModuleInterop": "Emit '__importStar' and '__importDefault' helpers for runtime babel ecosystem compatibility and enable '--allowSyntheticDefaultImports' for typesystem compatibility. Requires TypeScript version 2.7 or later.",
"esModuleInterop" : true,
"* @param: {boolean} allowJs": "Allow javascript files to be compiled.",
"allowJs": true,
"* @param: {node|classic} moduleResolution": "Specifies module resolution strategy: 'node' (Node) or 'classic' (TypeScript pre 1.6)",
"moduleResolution": "node",
"* @param: {boolean} allowSyntheticDefaultImports": "Allow default imports from modules with no default export. This does not affect code emit, just typechecking.",
"allowSyntheticDefaultImports": true,
"* @param: {Array<string>} typeRoots": "Specify list of directories for type definition files to be included. Requires TypeScript version 2.0 or later",
"typeRoots" : [
"./node_modules/@types",
"./@types"
],
"* @param: {boolean} strict": "Enable all strict type checking options. Requires TypeScript version 2.3 or later.",
"strict": false,
"* @param: {boolean} strictNullChecks": "Enable strict null checks. Requires TypeScript version 2.0 or later.",
"strictNullChecks": false,
"* @param: {boolean} resolveJsonModule": "Include modules imported with '.json' extension. Requires TypeScript version 2.9 or later.",
"resolveJsonModule": true,
"* @param: {string} baseUrl": "Base directory to resolve non-relative module names.",
"baseUrl": "./",
"* @param: {IPaths} paths": "Specify path mapping to be computed relative to baseUrl option.",
"paths": {
"@config/*": ["src/config/*"],
"@common/*": ["src/common/*"],
"@components/*": ["src/components/*"],
"@services/*": ["src/services/*"],
"@models/*": ["src/models/*"],
"@enums/*": ["src/enums/*"],
"@errors/*": ["src/models/errors/*"],
"@redux/*": ["src/redux/*"],
"@mocks/*": ["test/mocks/*"],
"@utils/*": ["src/utils/*"]
},
"* @param: {Array<string>} rootDirs": "Specify list of root directories to be used when resolving modules.",
"rootDirs": [
"src"
]
},
"* @param: {Array<string>} exclude": "Specifies a list of files to be excluded from compilation. The 'exclude' property only affects the files included via the 'include' property and not the 'files' property. Glob patterns require TypeScript version 2.0 or later.",
"exclude": ["node_modules"]
}
require('babel-polyfill');
const path = require('path');
const HtmlWebPackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const WebpackConfig = {
stats: {
warnings: false,
colors: true
},
/**
* @name Entry
* @description Start here
**/
entry: {
src : [
"babel-polyfill",
path.join(__dirname, "/src/index.tsx")
]
},
/**
* @name Resolve
* @description TS and TSX loader
* @param extensions - resolve in this order. Lookup .ts, then .tsx, then .js
* @param alias - alias to the path like a @path
* e.g. alias: {
* @utils: path.resolve(__dirname, 'src/utilities/'),
* }
*
* e.g. import Utility from '../../utilities/utility';
* import Utility from '@utils/utility';
**/
resolve : {
extensions : [".ts", ".tsx", ".js"],
alias : {
// handlebars: 'handlebars/dist/handlebars.min.js',
'@redux': path.resolve(__dirname, 'src/redux'),
}
},
/**
* @name ResolveLoaders
* @description Tell webpack where to look for loaders. By default it looks in `node_modules` but we want it to also look in `.webpack/loaders`
**/
resolveLoader: {
modules: [
'node_modules', /** this is the default */
path.resolve(__dirname,'.webpack/loaders')
]
},
module : {
rules: [
/**
* @name Typescript
* @description TS and TSX loader
**/
{
test : /\.tsx?$/,
use: [
'awesome-typescript-loader',
/**
* @name Example Loader
* @description example webpack loader from `.webpack/loaders/example-loader.js`
* @requires yarn add -D loader-utils
**/
{
loader: 'example-loader',
/** @requires yarn add -D loader-utils */
options: {
name: 'Some name'
}
}
]
},
/**
* @name Javascript
* @description JS loader
**/
{
enforce: "pre",
test: /\.js$/,
loader: "source-map-loader"
},
/**
* @name CSS
* @description CSS loader
**/
{
test : /\.css$/i,
use : ["style-loader", "css-loader"]
},
/**
* @name SASS
* @description SASS and SCSS loader. Reverse order.
**/
{
test: /\.s[ac]ss$/i,
use: [
/**
* 3. Creates `style` nodes from JS strings
**/
'style-loader',
/**
* 2. Translates CSS into CommonJS
**/
'css-loader',
/**
* 1. Compiles Sass to CSS
**/
'sass-loader',
],
},
/**
* @name Images
* @description Image loader
**/
{
test: /\.(png|svg|jpg|gif|jpe?g)$/,
use: [
{
options: {
name: "[name].[ext]",
outputPath: "assets/imgs/"
},
loader: "file-loader"
}
]
}
]
},
plugins: [
/**
* @name Images
* @namespace plugins
* @description Update the HTML static page
**/
new HtmlWebPackPlugin({
template : "./src/index.html"
}),
/**
* @name CopyWebpackPlugin
* @namespace plugins
* @description Copy the css and image assets to the dist folder
**/
new CopyWebpackPlugin([
{
from:'src/assets',
to:'assets'
}
]),
],
/**
* @name externals
* @description Exclude from bundling
* When importing a module whose path matches one of the following, just
* assume a corresponding global variable exists and use that instead.
* This is important because it allows us to avoid bundling all of our
* dependencies, which allows browsers to cache those libraries between builds.
**/
// externals: {
// 'react': 'React',
// 'react-dom': 'ReactDOM'
// }
}
module.exports = WebpackConfig;
const webpack = require('webpack');
const merge = require('webpack-merge');
const common = require('./webpack.common');
module.exports = merge(common, {
mode : "development",
// devtool : 'inline-source-map',
devtool: "source-map",
devServer : {
port: 8080,
host: (process.env.NODE_ENV === 'local' ? '127.0.0.1' : '0.0.0.0')
},
plugins : [
(() => {
return new webpack.DefinePlugin({
'process.env.random' : JSON.stringify("Hello world!")
})
})(),
]
})
/**
* @name WebpackLoader
* @description Must be a function.
* @usage `config.loaders.push({ })`
* @this - `this` webpack binds config to the context of this
* @param {string} source - source file as a string
* @returns {string} transformed - source file transformed
**/
const WebpackLoader = function(source){
/**
* @param {string} source - source file as a string
**/
var transformed = source;
/**
* @usage `this` is a reference to webpack config
**/
console.log('🦄 Transformation from `source` to `transformed`:', {source, transformed, _this: this});
/**
* @returns {string} transformed - source file transformed
**/
return transformed;
}
module.exports = WebpackLoader;
function FileListPlugin(options) {}
FileListPlugin.prototype.apply = function(compiler) {
compiler.plugin('emit', function(compilation, callback) {
// Create a header string for the generated file:
var filelist = 'In this build:\n\n';
// Loop through all compiled assets,
// adding a new line item for each filename.
for (var filename in compilation.assets) {
filelist += ('- '+ filename +'\n');
}
// Insert this list into the Webpack build as a new file asset:
compilation.assets['filelist.md'] = {
source: function() {
return filelist;
},
size: function() {
return filelist.length;
}
};
callback();
});
};
module.exports = FileListPlugin;
#!/bin/bash
printf "\n\n🥝🥝🥝\n"
printf "What is the path to the installation root?"
printf "\n🥝🥝🥝\n\n"
varRoot=./
read varRoot
echo Opening the directory: $varRoot
#
# @description change to dir
# @tutorial https://stackoverflow.com/questions/3349105/how-to-set-current-working-directory-to-the-directory-of-the-script
#
cd $varRoot
ls
pwd
#
# @name Loaders
# @description Install some example webpack loaders
#
mkdir -p .webpack/loaders
#
# @name Example Webpack Loader
# @description Install some example webpack loaders
# @param {string} exampleLoaderUrl - url to download from
# @param {string} exampleLoaderFilename - name of the file
#
exampleLoaderUrl=https://gist.githubusercontent.com/mitni455/32958a1df2a2e5c1e5dcdbde5bab0136/raw/e0d7357dac0627750afe4b563bed67c801bca3fb/webpack.example.loader.js
exampleLoaderFilename=webpack.example.loader.js
renameExampleLoaderFilename=example-loader.js
wget $exampleLoaderUrl --output-document=$exampleLoaderFilename
mv $exampleLoaderFilename .webpack/loaders/$renameExampleLoaderFilename
#
# @name ResolveLoaders
# @description Tell webpack where to look for loaders. By default it looks in `node_modules` but we want it to also look in `.webpack/loaders`
#
# @todo - add this to webpack config
# /**
# * @name ResolveLoaders
# * @description Tell webpack where to look for loaders. By default it looks in `node_modules` but we want it to also look in `.webpack/loaders`
# **/
# resolveLoader: {
# modules: ['node_modules', path.resolve(__dirname,'.webpack/loaders')]
# },
# @todo - add to `rules`
# /**
# * @name Typescript
# * @description TS and TSX loader
# **/
# {
# test : /\.tsx?$/,
# use: [
# 'awesome-typescript-loader',
# 'example-loader' /** example webpack loader from `.webpack/loaders/example-loader.js` */
# ]
# },
#
# @name options
# @description Loader utils to use options with module.rules
#
yarn add -D loader-utils
# @todo -
# use: [
# {
# exampleLoader: 'example-loader', /** example webpack loader from `.webpack/loaders/example-loader.js` */
# /** @requires yarn add -D loader-utils */
# options: {
# name: 'Some name'
# }
# }
# ]
const webpack = require('webpack');
const merge = require('webpack-merge');
const common = require('./webpack.common.js');
module.exports = merge(common, {
mode: "production",
plugins: [
]
})
#!/bin/bash
printf "\n\n🥝🥝🥝\n"
printf "What is the path to the installation root?"
printf "\n🥝🥝🥝\n\n"
varRoot=./
read varRoot
echo Opening the directory: $varRoot
#
# @description change to dir
# @tutorial https://stackoverflow.com/questions/3349105/how-to-set-current-working-directory-to-the-directory-of-the-script
#
cd $varRoot
ls
pwd
#
# @name Webpack common config
# @description Create common config
#
wget https://gist.githubusercontent.com/mitni455/32958a1df2a2e5c1e5dcdbde5bab0136/raw/705f6509b47b694650df90a0e5d80808d5544419/webpack.common.js --output-document=webpack.common.js
#
# @name Webpack dev config
# @description Create common config
#
wget https://gist.githubusercontent.com/mitni455/32958a1df2a2e5c1e5dcdbde5bab0136/raw/705f6509b47b694650df90a0e5d80808d5544419/webpack.dev.js --output-document=webpack.dev.js
#
# @name Webpack prod config
# @description Create common config
#
wget https://gist.githubusercontent.com/mitni455/32958a1df2a2e5c1e5dcdbde5bab0136/raw/705f6509b47b694650df90a0e5d80808d5544419/webpack.prod.js --output-document=webpack.prod.js
#
# @name Webpack
# @description Add webpack
#
yarn add -D webpack
yarn add -D webpack-cli
#
# @name Plugins
# @description Add webpack plugins
#
yarn add -D html-webpack-plugin
yarn add -D copy-webpack-plugin
#
# @name Package.json
# @description Add build to package.json scripts
#
# npm install -g json
json -I -f package.json -e 'this.scripts["build:dev"]="webpack --config webpack.dev.js" '
json -I -f package.json -e 'this.scripts["build:prod"]="webpack --config webpack.prod.js" '
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment