Skip to content

Webpack

Mingtao edited this page Dec 9, 2020 · 6 revisions
mkdir webpack-tutorial
cd webpack-tutorial
npm init -y # Generates package.json
npm install webpack webpack-cli --save-dev # Install webpack dependency

Create js files

npx webpack # Generates main.js under dist folder

package.json

"scripts": {
    "build": "webpack"
}

npm run build is equal to npx webpack

Import picture

js

import Kiwi from './details.png';

webpack.config.js

module.exports = {
    ...
    module: {
        rules: [
            {
                test: /\.(png|jpg)$/,
                use: [
                    'file-loader'
                ]
            }
        ]
    }
}

npm install file-loader --save-dev

package.json

"devDependencies": {
  "file-loader": "^6.2.0",
  ...
}

Import sass

webpack.config.js

module.exports = {
    ...
    module: {
        rules: [
            {
                test: /\.scss$/,
                use: ['style-loader', 'css-loader', 'sass-loader']
            }
        ]
    }
}

npm install sass-loader node-sass --save-dev

Use babel to convert js to old style

js

class HelloWorldButton {

    buttonCssClass = 'hello-world-button'

}

webpack.config.js

{
    test: /\.js$/,
    exclude: /node_modules/,
    use: {
        loader: 'babel-loader',
        options: {
            presets: ['@babel/env'],
            plugins: ['@babel/plugin-proposal-class-properties']
        }
    }
}

npm install @babel/core babel-loader @babel/preset-env @babel/plugin-proposal-class-properties --save-dev

Notes:

  • import helloWorld from './hello-world.js'; can be shortened to import helloWorld from './hello-world'
  • By default, webpack looks for src/index.js as the entry point. The "main": "index.js", in package.json is totally unrelated. The entry point is specified in the webpack.config.js file: entry: './src/index.js
Clone this wiki locally