Create Webpack Configuration File

Here I will add a config file and css

Create webpack.config.js file in root dir.

  • touch webpack.config.js

webpack.config.js

const path = require('path')

module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  }
}
  • Edit index.html script src from main.js to bundle.js

index.html

<script src="bundle.js"></script>
  • If you run npm run build again it will use this config file this time and will give us /dist/bundle.js instead of main.js, but other then that this is the same setup as the zero config. So lets make it do something cool!

Adding css

  • Get the proper webpack loaders, style-loader and css-loader.
    • yarn add style-loader css-loader
  • Create a new file in the src dir.
    • touch src/style.css

style.css

 .title {
  font-size: 40px;
  color: #444;
  font-family: sans-serif;
}
  • import style.css into your index.js

index.js

    /*+*/ import './style.css'

    var title = document.createElement('div')

    /*+*/ title.className = 'title'

    title.innerText = "Hello Webpack!"

    document.body.appendChild(title)
  • Add the necicery loaders to the webpack configuration

webpack.config.js

    const path = require('path')

    module.exports = {
      mode: 'development', /* Let webpack know we are in development */
      entry: './src/index.js',
      output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist')
      },
      module: {
        rules: [
          {
            test: /\.css$/,
            use: [
              {loader: 'style-loader'},
              {loader: 'css-loader'}
            ]
          }
        ]
      }
    }

Webpack will now import the css file and bundle it with the javascript. Later I will extract the css from the javascript. When using a lot of css this is a good idea, css and javascript load at the same time in the DOM, but having css in javascript will slow down load times.

For more info about importing assets check out webpack's documentation here

results matching ""

    No results matching ""