Lumpat menyang isi utama Lumpat menyang pandhu arah docs
Check
in English

Bootstrap & Webpack

Pandhuan resmi babagan cara nyakup lan mbundel CSS lan JavaScript Bootstrap ing proyek sampeyan nggunakake Webpack.

Pengin skip nganti pungkasan? Ngundhuh kode sumber lan demo sing digunakake kanggo pandhuan iki saka gudang twbs/conto . Sampeyan uga bisa mbukak conto ing StackBlitz kanggo nyunting langsung.

Setup

Kita lagi mbangun proyek Webpack nganggo Bootstrap saka awal, mula ana sawetara prasyarat lan langkah ngarep sadurunge bisa miwiti. Pandhuan iki mbutuhake sampeyan duwe Node.js diinstal lan sawetara menowo karo terminal.

  1. Nggawe folder proyek lan persiyapan npm. Kita bakal nggawe my-projectfolder lan miwiti npm kanthi -yargumen supaya ora takon kabeh pitakonan interaktif.

    mkdir my-project && cd my-project
    npm init -y
    
  2. Instal Webpack. Sabanjure kita kudu nginstal dependensi pangembangan Webpack: webpackkanggo inti saka Webpack, webpack-clisupaya kita bisa mbukak printah Webpack saka terminal, lan webpack-dev-serversupaya kita bisa mbukak server pangembangan lokal. Kita digunakake --save-devkanggo sinyal sing dependensi iki mung kanggo pembangunan lan ora kanggo produksi.

    npm i --save-dev webpack webpack-cli webpack-dev-server
    
  3. Instal Bootstrap. Saiki kita bisa nginstal Bootstrap. Kita uga bakal nginstal Popper amarga dropdowns, popovers, lan tooltips gumantung ing posisi. Yen sampeyan ora rencana nggunakake komponen kasebut, sampeyan bisa ngilangi Popper ing kene.

    npm i --save bootstrap @popperjs/core
    
  4. Instal dependensi tambahan. Saliyane Webpack lan Bootstrap, kita butuh sawetara dependensi kanggo ngimpor lan mbundel CSS lan JS Bootstrap kanthi bener karo Webpack. Iki kalebu Sass, sawetara loader, lan Autoprefixer.

    npm i --save-dev autoprefixer css-loader postcss-loader sass sass-loader style-loader
    

Saiki kita wis nginstal kabeh dependensi sing dibutuhake, kita bisa nggawe file proyek lan ngimpor Bootstrap.

Struktur proyek

Kita wis nggawe my-projectfolder kasebut lan miwiti npm. Saiki kita uga bakal nggawe srclan distfolder kanggo ngrampungake struktur proyek. Jalanake ing ngisor iki saka my-project, utawa nggawe folder lan struktur file kanthi manual ing ngisor iki.

mkdir {dist,src,src/js,src/scss}
touch dist/index.html src/js/main.js src/scss/styles.scss webpack.config.js

Yen wis rampung, proyek lengkap sampeyan kudu katon kaya iki:

my-project/
├── dist/
│   └── index.html
├── src/
│   ├── js/
│   │   └── main.js
│   └── scss/
│       └── styles.scss
├── package-lock.json
├── package.json
└── webpack.config.js

Ing wektu iki, kabeh ana ing panggonan sing bener, nanging Webpack ora bisa digunakake amarga kita durung ngisi webpack.config.js.

Konfigurasi Webpack

Kanthi dependensi diinstal lan folder proyek kita siap kanggo miwiti coding, saiki kita bisa ngatur Webpack lan mbukak proyek kita sacara lokal.

  1. Bukak webpack.config.jsing editor sampeyan. Amarga kosong, kita kudu nambah sawetara konfigurasi boilerplate supaya bisa miwiti server. Iki bagean saka config ngandhani Webpack padha kanggo nggoleki JavaScript project kita, ngendi kanggo output kode nyawiji kanggo ( dist), lan carane server pembangunan kudu nindakake (narik saka distfolder karo panas maneh).

    const path = require('path')
    
    module.exports = {
      entry: './src/js/main.js',
      output: {
        filename: 'main.js',
        path: path.resolve(__dirname, 'dist')
      },
      devServer: {
        static: path.resolve(__dirname, 'dist'),
        port: 8080,
        hot: true
      }
    }
    
  2. Sabanjure kita ngisi kita dist/index.html. Iki minangka kaca HTML sing bakal dimuat Webpack ing browser kanggo nggunakake CSS lan JS sing dibuntel sing bakal ditambahake ing langkah sabanjure. Sadurunge kita bisa nindakake iku, kita kudu menehi soko kanggo nerjemahake lan kalebu outputJS saka langkah sadurunge.

    <!doctype html>
    <html lang="en">
      <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Bootstrap w/ Webpack</title>
      </head>
      <body>
        <div class="container py-4 px-3 mx-auto">
          <h1>Hello, Bootstrap and Webpack!</h1>
          <button class="btn btn-primary">Primary button</button>
        </div>
        <script src="./main.js"></script>
      </body>
    </html>
    

    Kita kalebu sawetara gaya Bootstrap ing kene kanthi div class="container"lan <button>supaya kita bisa ndeleng nalika CSS Bootstrap dimuat dening Webpack.

  3. Saiki kita butuh skrip npm kanggo mbukak Webpack. Bukak package.jsonlan tambahake startskrip sing ditampilake ing ngisor iki (sampeyan kudu duwe skrip tes). Kita bakal nggunakake skrip iki kanggo miwiti server dev Webpack lokal kita.

    {
      // ...
      "scripts": {
        "start": "webpack serve --mode development",
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      // ...
    }
    
  4. Lan pungkasane, kita bisa miwiti Webpack. Saka my-projectfolder ing terminal sampeyan, jalanake skrip npm sing mentas ditambahake:

    npm start
    
    Webpack dev server mlaku

Ing bagean sabanjure lan pungkasan kanggo pandhuan iki, kita bakal nyiyapake loader Webpack lan ngimpor kabeh CSS lan JavaScript Bootstrap.

Ngimpor Bootstrap

Ngimpor Bootstrap menyang Webpack mbutuhake loader sing diinstal ing bagean pisanan. Kita wis nginstal npm, nanging saiki Webpack kudu dikonfigurasi supaya bisa digunakake.

  1. Setel loader ing webpack.config.js. Berkas konfigurasi sampeyan saiki wis rampung lan kudu cocog karo cuplikan ing ngisor iki. Siji-sijine bagean anyar ing kene yaiku modulebagean kasebut.

    const path = require('path')
    
    module.exports = {
      entry: './src/js/main.js',
      output: {
        filename: 'main.js',
        path: path.resolve(__dirname, 'dist')
      },
      devServer: {
        static: path.resolve(__dirname, 'dist'),
        port: 8080,
        hot: true
      },
      module: {
        rules: [
          {
            test: /\.(scss)$/,
            use: [
              {
                loader: 'style-loader'
              },
              {
                loader: 'css-loader'
              },
              {
                loader: 'postcss-loader',
                options: {
                  postcssOptions: {
                    plugins: () => [
                      require('autoprefixer')
                    ]
                  }
                }
              },
              {
                loader: 'sass-loader'
              }
            ]
          }
        ]
      }
    }
    

    Mangkene ringkesan kenapa kita butuh kabeh loader iki. style-loadernyuntikaken CSS menyang <style>unsur ing <head>saka kaca HTML, css-loadermbantu karo nggunakake @importlan url(), postcss-loaderdibutuhake kanggo Autoprefixer, lan sass-loaderngidini kita nggunakake Sass.

  2. Saiki, ayo ngimpor CSS Bootstrap. Tambah ing ngisor iki kanggo src/scss/styles.scssngimpor kabeh sumber Bootstrap Sass.

    // Import all of Bootstrap's CSS
    @import "~bootstrap/scss/bootstrap";
    

    Sampeyan uga bisa ngimpor stylesheet kanthi individu yen sampeyan pengin. Waca dokumen impor Sass kanggo rincian.

  3. Sabanjure, kita mbukak CSS lan ngimpor JavaScript Bootstrap. Tambah ing ngisor iki kanggo src/js/main.jsmbukak CSS lan ngimpor kabeh JS Bootstrap. Popper bakal diimpor kanthi otomatis liwat Bootstrap.

    // Import our custom CSS
    import '../scss/styles.scss'
    
    // Import all of Bootstrap's JS
    import * as bootstrap from 'bootstrap'
    

    Sampeyan uga bisa ngimpor plugin JavaScript siji-siji yen perlu supaya ukuran bundle mudhun:

    import Alert from 'bootstrap/js/dist/alert'
    
    // or, specify which plugins you need:
    import { Tooltip, Toast, Popover } from 'bootstrap'
    

    Waca dokumen JavaScript kanggo informasi luwih lengkap babagan cara nggunakake plugin Bootstrap.

  4. Lan sampeyan wis rampung! 🎉 Kanthi sumber Bootstrap Sass lan JS dimuat kanthi lengkap, server pangembangan lokal sampeyan saiki bakal katon kaya iki.

    Server dev Webpack mlaku nganggo Bootstrap

    Saiki sampeyan bisa miwiti nambah komponen Bootstrap sing pengin digunakake. Priksa manawa sampeyan mriksa proyek conto Webpack lengkap babagan cara nyakup Sass khusus tambahan lan ngoptimalake bangunan kanthi ngimpor mung bagean CSS lan JS Bootstrap sing sampeyan butuhake.

Optimizations produksi

Gumantung ing persiyapan sampeyan, sampeyan bisa uga pengin ngleksanakake sawetara keamanan tambahan lan optimasi kacepetan migunani kanggo mbukak proyek ing produksi. Elinga yen optimasi iki ora ditrapake ing proyek conto Webpack lan sampeyan kudu ngetrapake.

Ekstrak CSS

Sing dikonfigurasi ing ndhuwur kanthi gampang ngetokake CSS menyang bundel supaya ora perlu style-loadermbukak file CSS kanthi manual . dist/index.htmlPendekatan iki bisa uga ora bisa digunakake karo Kabijakan Keamanan Konten sing ketat, nanging bisa uga dadi kemacetan ing aplikasi sampeyan amarga ukuran bundel sing gedhe.

Kanggo misahake CSS supaya kita bisa mbukak langsung saka dist/index.html, gunakake mini-css-extract-loaderplugin Webpack.

Pisanan, instal plugin:

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

Banjur instantiate lan gunakake plugin ing konfigurasi Webpack:

--- a/webpack/webpack.config.js
+++ b/webpack/webpack.config.js
@@ -1,8 +1,10 @@
+const miniCssExtractPlugin = require('mini-css-extract-plugin')
 const path = require('path')
 
 module.exports = {
   mode: 'development',
   entry: './src/js/main.js',
+  plugins: [new miniCssExtractPlugin()],
   output: {
     filename: "main.js",
     path: path.resolve(__dirname, "dist"),
@@ -18,8 +20,8 @@ module.exports = {
         test: /\.(scss)$/,
         use: [
           {
-            // Adds CSS to the DOM by injecting a `<style>` tag
-            loader: 'style-loader'
+            // Extracts CSS for each JS file that includes CSS
+            loader: miniCssExtractPlugin.loader
           },
           {

Sawise mlaku npm run buildmaneh, bakal ana file anyar dist/main.css, sing bakal ngemot kabeh CSS sing diimpor dening src/js/main.js. Yen sampeyan ndeleng dist/index.htmling browser saiki, gaya kasebut bakal ilang, kaya saiki ing dist/main.css. Sampeyan bisa nyakup CSS sing digawe dist/index.htmlkaya iki:

--- a/webpack/dist/index.html
+++ b/webpack/dist/index.html
@@ -3,6 +3,7 @@
   <head>
     <meta charset="utf-8">
     <meta name="viewport" content="width=device-width, initial-scale=1">
+    <link rel="stylesheet" href="./main.css">
     <title>Bootstrap w/ Webpack</title>
   </head>
   <body>

Ekstrak file SVG

CSS Bootstrap kalebu macem-macem referensi menyang file SVG liwat data:URI inline. Yen sampeyan nemtokake Kebijakan Keamanan Konten kanggo proyek sampeyan sing ngalangi data:URI kanggo gambar, file SVG iki ora bakal dimuat. Sampeyan bisa ngatasi masalah iki kanthi ngekstrak file SVG inline nggunakake fitur modul aset Webpack.

Konfigurasi Webpack kanggo ngekstrak file SVG inline kaya iki:

--- a/webpack/webpack.config.js
+++ b/webpack/webpack.config.js
@@ -16,6 +16,14 @@ module.exports = {
   },
   module: {
     rules: [
+      {
+        mimetype: 'image/svg+xml',
+        scheme: 'data',
+        type: 'asset/resource',
+        generator: {
+          filename: 'icons/[hash].svg'
+        }
+      },
       {
         test: /\.(scss)$/,
         use: [

Sawise mlaku npm run buildmaneh, sampeyan bakal nemokake file SVG sing diekstrak dist/iconslan dirujuk kanthi bener saka CSS.


Ndeleng soko salah utawa ketinggalan jaman kene? Mangga mbukak masalah ing GitHub . Perlu bantuan kanggo ngatasi masalah? Telusuri utawa miwiti diskusi ing GitHub.