Webpack từ A đến Á: Webpack multiple entry points (ok)

https://kentrung256.blogspot.com/2020/07/webpack-multiple-entry-points.html

Webpack từ A đến Á: Webpack multiple entry points

July 29, 2020 webpackBài hôm nay chúng ta tìm hiểu về quản lí output với nhiều file đầu vào entry, tên của các file output sẽ dựa vào tên của các entry.

Nội dung chính

  • 1. Chuẩn bị file

  • 2. Cấu hình multiple entry point

  • 3. Cấu hình output

  • 4. Tổng kết file webpack.config.js

1. Chuẩn bị file

Code file webpack.config.js ban đầu


const path = require('path')

module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'main.js',
    path: path.resolve(__dirname, 'dist')
  }
}

Trước khi tìm hiểu vấn đề chúng ta ngó lại một chút file webpack.config.js


const path = require('path')

module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'main.js',
    path: path.resolve(__dirname, 'dist')
  }
}

Tạo file src/index.js


console.log('Hello World!')

2. Cấu hình multiple entry point

Trước khi tìm hiểu vấn đề chúng ta ngó lại một chút file webpack.config.js chỗ đoạn entry point


module.exports = {
  entry: './src/index.js',
  ...
}

Ta thấy entry đang là Single Entry, thực ra đây chỉ là kiểu viết shorthand của


entry: {
  main: './src/index.js'
}

Bây giờ các bạn tạo thêm file src/my-test.js và code bên trong đơn giản thế này


console.log('kentrung test')

Nếu muốn entry point nhận file js ở trên ta viết thêm cặp key-value với key là tên nào cũng được, value là đường dẫn tới file my-test.js


entry: {
  main: './src/index.js',
  myTest: './src/my-test.js'
}

3. Cấu hình output

Sau khi sửa lại entry, giờ ta sửa tiếp output


output: {
  filename: '[name].js',
  path: path.resolve(__dirname, 'dist')
}

Nội dung trên cho biết, với hai file đầu vào là mainmyTest sẽ được output ra các file với tên tương ứng, lấy hai tên này đổ vào [name] là main.jsmyTest.js Chạy lại webpack với npm run dev để áp dụng cấu hình mới. Bạn vào folder dist nếu thấy đúng là có thêm hai file main.js và myTest.js thì chúng ta đã test thành công output với nhiều đầu vào entry.

4. Tổng kết file webpack.config.js


const path = require('path')

module.exports = {
  entry: {
    main: './src/index.js',
    myTest: './src/my-test.js'
  },
  output: {
    filename: '[name].js',
    path: path.resolve(__dirname, 'dist')
  }
}

Last updated

Navigation

Lionel

@Copyright 2023