How to install Webpack
Published: 2020-12-30 16:21:12

You will need to install:

`npm install --save-dev webpack-cli`

add new script to package.json 
`"build": "webpack"`

then run npm build.

First step is to edit your create a webpack.config.js file

place this code inside:

`module.exports = {
  entry: './src/index.js',
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'main.js',
  },
  module: {
       rules: [
          {
                test: /\.js$/,
                exclude: /node_modules/,
                loader: "babel-loader",
          },
          {
                test: /\.html$/,
                use: [{ loader: "html-loader"}],
                },
                {
                    test: /\.scss$/,
                    use: [ 'style-loader', 'css-loader', 'sass-loader' ]
                }
       ]
 },
  plugins: [
    new HtmlWebPackPlugin({
           template: "./src/html/index.html",
           filename: "./index.html",
    })
  ]
}`

You will need to install the HTMLWebpackPlugin:
npm i --save-dev html-webpack-plugin

npm install --save-dev mini-css-extract-plugin


The rules are looking for what type of files to pay attention to or exclude.

Now we need to make sure our package.json looks like this:

`{
  "name": "travel_capstone",
  "version": "1.0.0",
  "description": "something",
  "main": "webpack.config.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack",
    "start": "node src/server/index.js"

  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/brookebachman/capstone_project_udacity.git"
  },
  "author": "",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/brookebachman/capstone_project_udacity/issues"
  },
  "homepage": "https://github.com/brookebachman/capstone_project_udacity#readme",
  "devDependencies": {
    "html-webpack-plugin": "^4.5.0",
    "mini-css-extract-plugin": "^1.3.3",
    "webpack-cli": "^4.3.0"
  },
  "dependencies": {
    "babel-loader": "^8.2.2",
    "html-loader": "^1.3.2",
    "webpack": "^5.11.1",
    "workbox-webpack-plugin": "^6.0.2"
  }
}
`
install any dependencies you are missing with npm i command.

at this point run this command:

npm run build.

It gives detailed error messages so go through those until it looks something like this.

`BREAKING CHANGE: No more changes should happen to Compilation.assets after sealing the Compilation.
        Do changes to assets earlier, e. g. in Compilation.hooks.processAssets.
        Make sure to select an appropriate stage from Compilation.PROCESS_ASSETS_STAGE_*.
(Use `node --trace-deprecation ...` to show where the warning was created)
asset main.js 800 bytes [emitted] (name: main)
asset ./index.html 31 bytes [compared for emit]
./src/client/index.js 1 bytes [built] [code generated]
webpack 5.11.1 compiled successfully in 477 ms`

If it was successful you should now have a dist file.

Webpack generates this for you.

NEVER EDIT THESE FILES.

They get generated from your code. If you edit anything in the dist file it will be overwritten.

next create a .babelrc file in your root folder.

Enter this code:

`{'presets': '@babel/preset-env'}`

Make sure to install your babel-loader:

npm i -D @babel/core @babel/preset-env babel-loader

Now if you have js files that you want dist to know about you will import them to your './src/client/index.js' file.

Because of our loaders and plugins we get special features like import statements.

Say we have a handleSubmit.js file in client.

We can now import this file into webpack.

In 'src/client/index.js'

We can write:

`import {handleSubmit} from './src/client/js/handleSubmit.js`

Now make sure to go to your handleSubmit file and export your function.

`async function handleSubmit(event, defaultText) {
	event.preventDefault();
	console.log('handleSubmit is running');
	const text = defaultText || getTextValue()
	// const baseUrl = `https://api.meaningcloud.com/lang-2.0?key=${apiKey}&txt=${text}`
	const baseUrl = 'http://localhost:8081/test';
	const data = await fetch(baseUrl, {
		method: 'POST',
		headers: {
			'Content-Type': 'application/json',
		},
		body: JSON.stringify({
			text: text,
		}),
	})
		.then((resp) => resp.json())
        Client.postToFrontend(data);
        return data
}

function getTextValue(){
    const text = document.getElementById('someText').value;
    return text

}


export { handleSubmit };
`

Next let's set up our server.
 Install these dependencies:

`const dotenv = require('dotenv');
var path = require('path');
const express = require('express');
var cors = require('cors');
const app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
const fetch = require('node-fetch');

dotenv.config();
app.use(express.static('dist'));
app.use(cors());

Now let's set up our home page path.
We now know our index.html that we want to run is in our dist folder.

app.get('/', function(req,res){
    res.sendFile('dist/index.html')
})`

Now we are going to create our different Modes.

First open package.json.

In scripts:

Replace "build": "webpack"
with 
` "build-prod": "webpack --config webpack.prod.js",
"build-dev": "webpack-dev-server  --config webpack.dev.js --open"
},`

Now in the root folder create webpack.prod.js file. You should also change webpack.config.js to webpack.dev.js.

Inside of both of your webpack files.

add a mode either 'production' or 'development'.

It should look like this:

`module.exports = {
    entry: './src/client/index.js',
    mode: 'production',
    module: {
         rules: [
            {
                  test: /\.js$/,
                  exclude: /node_modules/,
                  loader: "babel-loader",
            },
            {
                  test: /\.html$/,
                  use: [{ loader: "html-loader"}],
                  },
                  {
                      test: /\.scss$/,
                      use: [ 'style-loader', 'css-loader', 'sass-loader' ]
                  }
         ]
   },
    plugins: [
      new HtmlWebpackPlugin({
             template: "./src/client/views/index.html",
             filename: "./index.html",
      })
    ]
}`

Now we want to remove the original dev server with this command.

First let's run this command.

If you get an error saying no webpack-dev-server enter this command

npm install webpack-dev-server -g

npm i -D clean-webpack-plugin

Now add this to your webpack.config.js file

const { CleanWebpackPlugin } = require('clean-webpack-plugin');

Let's set some special settings in the plugins.

`new CleanWebpackPlugin({
        // Simulate the removal of files
        dry: true,
        // Write Logs to Console
        verbose: true,
        // Automatically remove all unused webpack assets on rebuild
        cleanStaleWebpackAssets: true,
        protectWebpackAssets: false
})`

Okay now let's add some sass loaders.

Enter this command.

npm i -D style-loader node-sass css-loader sass-loader

add this to webpack.dev.js

output: {
     libraryTarget: 'var',
     library: 'Client'
 },

Now when we refer to the functions we refer to them with Client.handleSubmit

Make sure to not use link refs to stylesheet in index.html.

If you need to import any files to webpack always do them in index.js client.

If your dist file ever gets deleted.

run npm run-prod. This will recreate the dist file.