Skip to content

Instantly share code, notes, and snippets.

@MatMoore
Last active January 22, 2021 17:00
Show Gist options
  • Save MatMoore/ce7bcc719d7fed503f5ca672e6649898 to your computer and use it in GitHub Desktop.
Save MatMoore/ce7bcc719d7fed503f5ca672e6649898 to your computer and use it in GitHub Desktop.
Javascript tools cheat sheet

Tools covered by https://www.udemy.com/course/react-2nd-edition/learn/lecture/7707740, in the order they're introduced.

Liveserver

A web server

live-server public

Babel CLI

Compile modern stuff to shippable javascript

  • Env preset = ES6
  • React preset
babel src/app.js --out-file=public/scripts/app.js --presets=env,react --watch

Yarn

Create yarn run commands for each step, e.g. yarn run build.

package.json, with webpack:

  "scripts": {
    "build": "webpack",
    "dev-server": "webpack-dev-server"
  },

When using webpack, you don't need to run babel directly, and with webpack-dev-server, you don't need to run live-server and webpack --watch separately.

package.json, without webpack

  "scripts": {
    "build-babel": "babel src/app.js --out-file=public/scripts/app.js --presets=env,react --watch",
    "serve": "live-server public",
  },

Webpack

Combine javascript into a single resource

webpack.config.js:

const path= require('path');

module.exports = {
    entry: './src/app.js',
    'output': {
        path: path.join(__dirname, 'public'),
        filename: 'bundle.js'
    },
    'module': {
        rules: [{
            loader: 'babel-loader',
            test: /\.js$/,
            exclude: /node_modules/
        }]
    },
    'devtool': 'cheap-module-eval-source-map',
    'devServer': {
        contentBase: path.join(__dirname, 'public')
    }
};

contentBase is only needed when serving static files.

We're replacing the babel CLI with babel core, so we need a .babelrc file:

{
    "presets": ["@babel/preset-env", "@babel/preset-react"]
}

We now explicitly define dependencies in the package.json, so need to yarn add all of these:

  • react
  • react-dom
  • @babel/core
  • babel-loader
  • @babel/preset-env
  • @babel/preset-react

(Note: all babel packages have been changed from babel-foo to @babel/foo in v7)

CSS processing

There are two webpack loaders that work together for CSS, style-loader (which injects CSS into the page as <style> tags) and css-loader, which lets you use imports to show dependencies between CSS and Javascript files.

sass-loader and node-sass compile SASS/SCSS to CSS.

Rule for webpack.config.js:

          {
              test: /\.scss$/,
              loader: ['style-loader', 'css-loader', 'sass-loader']
          }

The order matters. If you reverse style-loader and css-loader, webpack gives a cryptic error.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment