Tsibela kumxholo ophambili Tsiba uye kukhangelo lwamaxwebhu
Check
in English

I-Bootstrap kunye neWebhupack

Isikhokelo esisemthethweni sendlela yokubandakanya kunye nokudibanisa i-Bootstrap's CSS kunye neJavaScript kwiprojekthi yakho usebenzisa iWebpack.

Ngaba ufuna ukutsiba ukuya esiphelweni? Khuphela ikhowudi yomthombo kunye nedemo yokusebenza kwesi sikhokelo kwi- twbs/imizekelo yokugcina . Unako kwakhona ukuvula umzekelo kwi-StackBlitz ukuze uhlele ngokuphila.

Misela

Sakha iprojekthi yeWebpack ngeBootstrap ukusuka ekuqaleni, ke kukho izinto eziyimfuneko kunye namanyathelo angaphambili ngaphambi kokuba siqalise ngokwenene. Esi sikhokelo sifuna ukuba ube neNode.js efakiweyo kunye nokuqhelana ne-terminal.

  1. Yenza ifolda yeprojekthi kunye nokuseta i-npm. Siza kudala my-projectifolda kwaye siqalise i-npm -yngengxoxo ukuyinqanda ukusibuza yonke imibuzo esebenzisanayo.

    mkdir my-project && cd my-project
    npm init -y
    
  2. Faka iWebpack. Okulandelayo kufuneka sifake ukuxhomekeka kwethu kophuhliso lweWebpack: webpackkwisiseko seWebpack, webpack-cliukuze sikwazi ukuqhuba imiyalelo yeWebpack kwi-terminal, kwaye webpack-dev-serverngoko sinokuqhuba umncedisi wophuhliso wendawo. Sisebenzisa --save-devukubonisa ukuba ezi zixhomekeke kuphela kusetyenziso lophuhliso kwaye hayi imveliso.

    npm i --save-dev webpack webpack-cli webpack-dev-server
    
  3. Faka i-Bootstrap. Ngoku sinokufaka i-Bootstrap. Siza kuphinda siyifake iPopper ukusukela oko ukwehla kwethu, iipopovers, kunye neengcebiso zesixhobo zixhomekeke kuyo ngokuma kwazo. Ukuba awucwangcisi ukusebenzisa ezo zixhobo, ungashiya iPopper apha.

    npm i --save bootstrap @popperjs/core
    
  4. Faka izinto ezixhomekeke kuzo ezongezelelweyo. Ukongeza kwi-Webpack kunye ne-Bootstrap, sifuna ukuxhomekeka okumbalwa ngakumbi ukungenisa ngokufanelekileyo kunye nokudibanisa i-CSS ye-Bootstrap kunye ne-JS nge-Webpack. Ezi ziquka i-Sass, ezinye izilayishi, kunye ne-Autoprefixer.

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

Ngoku ukuba sinabo bonke ukuxhomekeka okufunekayo okufakiweyo, sinokufika emsebenzini ukudala iifayile zeprojekthi kunye nokungenisa i-Bootstrap.

Ubume beprojekthi

Sele siyile my-projectifolda kwaye saqalisa i-npm. Ngoku siza kudala zethu srckunye distneefolda ukurhangqa ubume beprojekthi. Qhuba oku kulandelayo ukusuka my-project, okanye wenze ngesandla isiqulathi seefayili kunye nesakhiwo sefayile eboniswe ngezantsi.

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

Xa ugqibile, iprojekthi yakho epheleleyo kufuneka ijongeke ngolu hlobo:

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

Okwangoku, yonke into ikwindawo elungileyo, kodwa iWebpack ayizukusebenza kuba asikagcwalisi eyethu webpack.config.jsokwangoku.

Qwalasela iWebpack

Ngokuxhomekeka okufakwe kunye nefolda yethu yeprojekthi isilungele ukuba siqale ukubhalwa kweekhowudi, ngoku sinokuyilungisa iWebpack kwaye siqhube iprojekthi yethu kwindawo.

  1. Vula webpack.config.jskumhleli wakho. Kuba ingenanto, kuya kufuneka songeze i-boilerplate config kuyo ukuze siqalise umncedisi wethu. Le nxalenye yoqwalaselo ixelela iWebpack ukuba ijonge iJavaScript yeprojekthi yethu, apho izakuphuma khona ikhowudi eqokelelweyo ukuya ( dist), kwaye umncedisi wophuhliso kufuneka aziphathe njani (ukutsala distkwifolda ngokulayishwa kwakhona okushushu).

    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 sizalisa yethu dist/index.html. Eli liphepha le-HTML leWebhu eliza kulayisha kwibhrawuza ukusebenzisa i-CSS edityanisiweyo kunye ne-JS siya kuyongeza kuyo ekuhambeni kwexesha. Ngaphambi kokuba senze oko, kufuneka sinikeze into yokuyinikezela kwaye ibandakanye i- outputJS ukusuka kwinqanaba langaphambili.

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

    Sibandakanya isitayile esincinci seBootstrap apha kunye div class="container"kwaye <button>ukuze sibone xa i-Bootstrap's CSS ilayishwa yiWebpack.

  3. Ngoku sifuna iskripthi se-npm ukuqhuba iWebpack. Vula package.jsonkwaye wongeze startiskripthi esiboniswe ngezantsi (kufuneka ube sele unaso iskripthi sovavanyo). Siza kusebenzisa esi script ukuqalisa iseva yethu yeWebpack dev.

    {
      // ...
      "scripts": {
        "start": "webpack serve --mode development",
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      // ...
    }
    
  4. Kwaye ekugqibeleni, sinokuqala iWebpack. Ukusuka my-projectkwifolda kwi-terminal yakho, sebenzisa eso skripthi se-npm esitsha:

    npm start
    
    Iseva yeWebhu ye-dev iyasebenza

Kwicandelo elilandelayo kunye nelokugqibela kwesi sikhokelo, siya kuseka abalayishi beWebpack kwaye singenise yonke i-Bootstrap's CSS kunye neJavaScript.

Thatha ngaphandle i-Bootstrap

Ukungenisa i-Bootstrap kwi-Webpack kufuna abalayishi esibafake kwicandelo lokuqala. Sizifakile nge-npm, kodwa ngoku iWebpack kufuneka iqwalaselwe ukuze izisebenzise.

  1. Misela abalayishi kwi webpack.config.js. Ifayile yakho yoqwalaselo ngoku igqityiwe kwaye kufuneka ihambelane nesnippet engezantsi. Inxalenye entsha kuphela apha modulelicandelo.

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

    Nantsi inkcazo yokuba kutheni sifuna zonke ezi zilayishi. style-loaderitofa i CSS <style>kwinto kwiphepha <head>le HTML, css-loaderinceda ekusebenziseni @importkwaye url(), postcss-loaderiyafuneka kwi Autoprefixer, kwaye isivumela sass-loaderukuba sisebenzise iSass.

  2. Ngoku, masingenise i-CSS ye-Bootstrap. Yongeza oku kulandelayo src/scss/styles.scssukungenisa yonke imvelaphi yeBootstrap yeSass.

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

    Ungangenisa amaxwebhu ethu esitayile ngokwahlukeneyo ukuba uyafuna. Funda amaxwebhu wethu we-Sass wokungenisa iinkcukacha.

  3. Okulandelayo silayisha iCSS kwaye singenise iJavaScript yeBootstrap. Yongeza oku kulandelayo src/js/main.jsukulayisha iCSS kwaye ungenise yonke i-Bootstrap's JS. I-Popper iyakungeniswa ngaphandle ngokuzenzekelayo ngeBootstrap.

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

    Ungangenisa iiplagi zeJavaScript nganye nganye njengoko kufuneka ukugcina ubungakanani benqwaba phantsi:

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

    Funda amaxwebhu ethu eJavaScript ngolwazi olungakumbi malunga nendlela yokusebenzisa iiplagi zeBootstrap.

  4. Kwaye ugqibile! 🎉 Ngomthombo we-Bootstrap we-Sass kunye ne-JS elayishwe ngokupheleleyo, iseva yakho yophuhliso yasekhaya ngoku kufuneka ijongeke ngolu hlobo.

    Iseva yeWebhu ye-dev esebenza ngeBootstrap

    Ngoku ungaqala ukongeza naziphi na izinto zeBootstrap ofuna ukuzisebenzisa. Qinisekisa ukuba ujonge iprojekthi yomzekelo weWebpack epheleleyo yendlela yokubandakanya i-Sass yesiko elongezelelweyo kunye nokwandisa ukwakha kwakho ngokungenisa kuphela iinxalenye ze-Bootstrap's CSS kunye ne-JS oyifunayo.

Ukulungiswa kwemveliso

Ngokuxhomekeke kulungiselelo lwakho, unokufuna ukusebenzisa ukhuseleko olongezelelweyo kunye nesantya solungiselelo oluluncedo ekuqhubeni iprojekthi kwimveliso. Qaphela ukuba olu lungiso alusetyenziswanga kwiprojekthi yomzekelo weWebpack kwaye kuxhomekeke kuwe ukuba uyiphumeze.

Ukutsalwa kweCSS

Esiyiqwalaseleyo style-loaderngasentla ikhupha ngokulula iCSS kwinqwaba ukuze ukulayisha ngesandla ifayile yeCSS dist/index.htmlakuyomfuneko. Le ndlela isenokungasebenzi kunye noMgaqo-nkqubo woKhuseleko woMxholo ongqongqo, nangona kunjalo, kwaye inokuba ngumqobo kwisicelo sakho ngenxa yobukhulu benqwaba.

Ukwahlula i-CSS ukuze sikwazi ukuyilayisha ngokuthe ngqo ukusuka dist/index.html, sebenzisa mini-css-extract-loaderiplagi yeWebpack.

Okokuqala, faka i-plugin:

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

Emva koko qinisekisa kwaye usebenzise iplagin kuqwalaselo lweWebpack:

--- 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
           },
           {

Emva kokusebenza npm run buildkwakhona, kuyakubakho ifayile entsha dist/main.css, eya kuqulatha yonke i CSS ethathwe ngaphandle nge src/js/main.js. Ukuba ujonga kwisikhangeli dist/index.htmlsakho ngoku, isitayile siya kulahleka, njengoko sikhoyo ngoku dist/main.css. Ungabandakanya iCSS eyenziwe ngolu dist/index.htmlhlobo:

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

Kukhutshwa iifayile zeSVG

I-Bootstrap's CSS ibandakanya iireferensi ezininzi kwiifayile zeSVG nge-inline data:URIs. Ukuba uchaza uMgaqo-nkqubo woKhuseleko woMxholo weprojekthi yakho ovala data:ii-URI zemifanekiso, ezi fayile zeSVG aziyi kulayisha. Unokuyijikeleza le ngxaki ngokukhupha iifayile ze-SVG ezingaphakathi usebenzisa i-Webpack yeemodyuli ze-asethi.

Qwalasela iWebpack ukukhupha iifayile zeSVG ezingaphakathi ngolu hlobo:

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

Emva kokusebenza npm run buildkwakhona, uya kufumana iifayile zeSVG ezikhutshelweyo dist/iconskwaye zichazwe ngokufanelekileyo kwiCSS.


Uyabona into engalunganga okanye ephelelwe lixesha apha? Nceda uvule umba kwi-GitHub . Ngaba ufuna uncedo lokulungisa ingxaki? Khangela okanye uqale ingxoxo kwi-GitHub.