Yeqela kokuqukethwe okuyinhloko Yeqela ku-docs navigation
Check
in English

I-Bootstrap ne-Webpack

Umhlahlandlela osemthethweni wokuthi ungayifaka kanjani futhi uyihlanganise kanjani i-CSS ye-Bootstrap ne-JavaScript kuphrojekthi yakho usebenzisa i-Webpack.

Ufuna ukweqela ekupheleni? Dawuniloda ikhodi yomthombo kanye nedemo yokusebenza yalo mhlahlandlela endaweni yokugcina ye- twbs/izibonelo . Ungakwazi futhi ukuvula isibonelo ku-StackBlitz ukuze uhlele bukhoma.

Setha

Sakha iphrojekthi ye-Webpack nge-Bootstrap kusukela ekuqaleni, ngakho-ke kukhona izimfuneko ezithile kanye nezinyathelo zangaphambili ngaphambi kokuthi siqale ngempela. Lo mhlahlandlela udinga ukuthi ufake i-Node.js kanye nokujwayelana netheminali.

  1. Dala ifolda yephrojekthi bese usetha i-npm. Sizodala my-projectifolda futhi siqalise i-npm nge- -yagumenti ukuze siyigweme ukusibuza yonke imibuzo ephendulanayo.

    mkdir my-project && cd my-project
    npm init -y
    
  2. Faka i-Webpack. Okulandelayo sidinga ukufaka ukuncika kwethu kokuthuthukiswa kwe webpack-Webpack: kumnyombo weWebpack, webpack-cliukuze sikwazi ukusebenzisa imiyalo yeWebpack kusuka ku-terminal, webpack-dev-serverukuze sikwazi ukusebenzisa iseva yokuthuthukisa yasendaweni. Sisebenzisa --save-devukukhombisa ukuthi lokhu kuncika okokusetshenziswa kwentuthuko kuphela hhayi okokukhiqiza.

    npm i --save-dev webpack webpack-cli webpack-dev-server
    
  3. Faka i-Bootstrap. Manje sesingakwazi ukufaka i-Bootstrap. Sizophinda sifake i-Popper njengoba okwehliswayo kwethu, ama-popvers, namathiphu amathuluzi kuncike kuyo ukuze ibekwe. Uma ungahlelile ukusebenzisa lezo zingxenye, ungashiya i-Popper lapha.

    npm i --save bootstrap @popperjs/core
    
  4. Faka okuncikile okwengeziwe. Ngokungeziwe ku-Webpack ne-Bootstrap, sidinga ukuncika okwengeziwe okumbalwa ukuze singenise kahle futhi sihlanganise i-CSS ye-Bootstrap ne-JS nge-Webpack. Lokhu kufaka phakathi i-Sass, ezinye izilayishi, kanye ne-Autoprefixer.

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

Manje njengoba sesinakho konke ukuncika okudingekayo okufakiwe, singakwazi ukuqala umsebenzi ngokudala amafayela wephrojekthi futhi singenise i-Bootstrap.

Isakhiwo sephrojekthi

Sesivele my-projectsiyidalile ifolda futhi saqalisa i-npm. Manje sizophinde sidale ethu srckanye distnamafolda ukuze sihlanganise ukwakheka kwephrojekthi. Qalisa okulandelayo ukusuka ku- my-project, noma uzenzele ifolda nesakhiwo sefayela esiboniswe ngezansi.

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

Uma usuqedile, iphrojekthi yakho ephelele kufanele ibukeke kanje:

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

Njengamanje, yonke into isendaweni efanele, kodwa iWebpack ngeke isebenze ngoba asikakagcwalisi eyethu webpack.config.js.

Lungiselela i-Webpack

Njengoba okuncikile kufakiwe kanye nefolda yethu yephrojekthi isilungele ukuthi siqale ukubhala amakhodi, manje singakwazi ukumisa i-Webpack futhi siqhube iphrojekthi yethu endaweni.

  1. Vula webpack.config.jskusihleli sakho. Njengoba ingenalutho, kuzodingeka sengeze ukulungiselelwa kwe-boilerplate kuyo ukuze sikwazi ukuqala iseva yethu. Le ngxenye yokucushwa itshela i-Webpack ukuthi kufanele ibheke i-JavaScript yephrojekthi yethu, lapho izokhipha khona ikhodi ehlanganisiwe iye ku- ( dist), nokuthi iseva yokuthuthukisa kufanele iziphathe kanjani (idonsa distkufolda ngokulayisha kabusha okushisayo).

    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. Okulandelayo sigcwalisa dist/index.html. Leli yikhasi le-HTML le-Webpack elizolayishwa esipheqululini ukuze sisebenzise i-CSS ehlanganisiwe futhi i-JS sizoyengeza kuyo ngezinyathelo ezizayo. Ngaphambi kokuthi senze lokho, kufanele sikunikeze okuthile ukuze sikunikeze futhi sifake i- outputJS kusuka esinyathelweni sangaphambilini.

    <!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>
    

    Sifaka isitayela esincane se-Bootstrap lapha nokuthi div class="container"futhi <button>ukuze sibone lapho i-CSS ye-Bootstrap ilayishwa yi-Webpack.

  3. Manje sidinga iskripthi se-npm ukusebenzisa i-Webpack. Vula package.jsonbese wengeza startumbhalo oboniswe ngezansi (kufanele usunaso kakade umbhalo wokuhlola). Sizosebenzisa lesi script ukuze siqale iseva yethu yendawo ye-Webpack dev.

    {
      // ...
      "scripts": {
        "start": "webpack serve --mode development",
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      // ...
    }
    
  4. Futhi ekugcineni, singakwazi ukuqala i-Webpack. Kusuka my-projectkufolda ekutheminali yakho, sebenzisa lo mbhalo we-npm osanda kufakwa:

    npm start
    
    Iseva ye-Webpack dev iyasebenza

Esigabeni esilandelayo nesokugcina kulo mhlahlandlela, sizosetha izilayishi ze-Webpack futhi singenise yonke i-CSS ye-Bootstrap ne-JavaScript.

Ngenisa i-Bootstrap

Ukungenisa i-Bootstrap ku-Webpack kudinga izilayishi esizifakile esigabeni sokuqala. Sizifake nge-npm, kodwa manje i-Webpack idinga ukulungiswa ukuze iyisebenzise.

  1. Setha izilayishi ku- webpack.config.js. Ifayela lakho lokumisa seliqedile futhi kufanele lifane namazwibela angezansi. Okuwukuphela kwengxenye entsha lapha moduleisigaba.

    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'
              }
            ]
          }
        ]
      }
    }
    

    Nasi isifinyezo sokuthi kungani sidinga zonke lezi zilayishi. style-loaderijova i-CSS entweni ekhasini le- <style>HTML <head>, css-loaderisiza ekusebenziseni @importfuthi url(), postcss-loaderiyadingeka ku-Autoprefixer, futhi sass-loaderisivumela ukuthi sisebenzise i-Sass.

  2. Manje, ake singenise i-CSS ye-Bootstrap. Engeza okulandelayo ukuze src/scss/styles.scssungenise wonke umthombo we-Bootstrap's Sass.

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

    Ungangenisa futhi amashidi esitayela ethu ngawodwana uma ufuna. Funda amadokhumenti ethu okungenisa kwe-Sass ukuze uthole imininingwane.

  3. Okulandelayo silayisha i-CSS futhi singenise i-JavaScript ye-Bootstrap. Engeza okulandelayo ukuze src/js/main.jsulayishe i-CSS futhi ungenise yonke i-JS ye-Bootstrap. I-Popper izongeniswa ngokuzenzakalelayo nge-Bootstrap.

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

    Futhi ungangenisa ama-plugin e-JavaScript ngawodwana njengoba kudingeka ukuze ugcine osayizi benqwaba bephansi:

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

    Funda amadokhumenti ethu e-JavaScript ukuze uthole ulwazi olwengeziwe mayelana nendlela yokusebenzisa ama-plugin e-Bootstrap.

  4. Futhi usuqedile! 🎉 Ngomthombo we-Bootstrap i-Sass ne-JS zilayishwe ngokugcwele, iseva yakho yokuthuthukisa yasendaweni kufanele manje ibukeke kanje.

    Iseva ye-Webpack dev esebenza nge-Bootstrap

    Manje ungaqala ukwengeza noma yiziphi izingxenye ze-Bootstrap ofuna ukuzisebenzisa. Qiniseka ukuthi uhlola iphrojekthi yesibonelo seWebpack ephelele yokuthi ungafaka kanjani i-Sass yangokwezifiso eyengeziwe futhi uthuthukise isakhiwo sakho ngokungenisa kuphela izingxenye ze-Bootstrap's CSS ne-JS ozidingayo.

Ukulungiselelwa kokukhiqiza

Ngokuya ngokusetha kwakho, ungase ufune ukusebenzisa ukuvikeleka okwengeziwe kanye nokwenza ngcono isivinini okusebenzisekayo ekusebenziseni iphrojekthi ekukhiqizeni. Qaphela ukuthi lokhu kulungiselelwa akusetshenziswa kuphrojekthi yesibonelo se-Webpack futhi kukuwe ukuthi uyisebenzise.

Ikhipha i-CSS

Esikulungiselele style-loaderngenhla kukhipha kalula i-CSS kunqwaba ukuze ukulayisha mathupha ifayela le-CSS dist/index.htmlkungadingeki. Le ndlela ingase ingasebenzi ngeNqubomgomo Yokuphepha Kokuqukethwe eqinile, kodwa, futhi ingase ibe umgoqo kuhlelo lwakho lokusebenza ngenxa yosayizi omkhulu wenqwaba.

Ukuze uhlukanise i-CSS ukuze sikwazi ukuyilayisha ngokuqondile ku- dist/index.html, sebenzisa i-plugin ye- mini-css-extract-loaderWebpack.

Okokuqala, faka i-plugin:

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

Bese uqinisa futhi usebenzise i-plugin ekucushweni kwe-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
           },
           {

Ngemva kokusebenza npm run buildfuthi, kuzoba nefayela elisha dist/main.css, elizoqukatha wonke ama-CSS angeniswe ngu- src/js/main.js. Uma ubuka dist/index.htmlesipheqululini sakho manje, isitayela sizobe singekho, njengoba sinjalo manje ku- dist/main.css. Ungafaka i-CSS ekhiqizwe dist/index.htmlkanje:

--- 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>

Imonyula amafayela e-SVG

I-CSS ye-Bootstrap ihlanganisa izinkomba eziningi kumafayela e-SVG ngama- data:URI asemgqeni. Uma uchaza Inqubomgomo Yokuphepha Kokuqukethwe yephrojekthi yakho evimba ama data:-URI ezithombe, lawa mafayela e-SVG ngeke alayishe. Ungakwazi ukubhekana nale nkinga ngokukhipha amafayela e-SVG angaphakathi usebenzisa isici samamojula wefa weWebpack.

Lungiselela i-Webpack ukuze ukhiphe amafayela e-SVG asemgqeni kanje:

--- 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: [

Ngemva kokusebenza npm run buildfuthi, uzothola amafayela e-SVG ekhishiwe dist/iconsfuthi akhonjwe kahle ku-CSS.


Ubona okuthile okungalungile noma okudlulelwe yisikhathi lapha? Sicela uvule inkinga ku-GitHub . Udinga usizo lokuxazulula inkinga? Sesha noma uqale ingxoxo ku-GitHub.