Svetuka kune chikuru content Svetuka kuenda kudocs navigation
Check
in English

Bootstrap & Webpack

Nhungamiro yepamutemo yekubatanidza uye kuunganidza Bootstrap's CSS uye JavaScript mupurojekiti yako uchishandisa Webpack.

Unoda kusvetuka kusvika kumagumo? Dhawunirodha iyo kodhi kodhi uye yekushanda demo yegwaro iri kubva kune twbs/examples repository . Iwe unogona zvakare kuvhura iyo muenzaniso muStackBlitz yekurarama editing.

Gadzirira

Tiri kuvaka purojekiti yeWebpack neBootstrap kubva pakutanga, saka pane zvimwe zvinodikanwa uye nhanho dzepamberi tisati tanyatsotanga. Gwaro iri rinoda kuti iwe uve neNode.js yakaiswa uye kumwe kujairana neiyo terminal.

  1. Gadzira purojekiti folda uye setup npm. Isu tichagadzira iyo my-projectfolda uye totanga npm -ynekupokana kuti tidzivise kutibvunza mibvunzo yese inopindirana.

    mkdir my-project && cd my-project
    npm init -y
    
  2. Isa Webpack. Tevere isu tinofanirwa kuisa yedu Webpack kusimudzira kutsamira: webpackkune musimboti weWebpack, webpack-clisaka isu tinokwanisa kumhanya Webpack mirairo kubva kune terminal, uye webpack-dev-serverkuti tikwanise kumhanyisa sevha yekuvandudza yenzvimbo. Isu tinoshandisa --save-devkuratidza kuti izvi zvinotsamira ndezvekushandiswa kwekusimudzira kwete kugadzira.

    npm i --save-dev webpack webpack-cli webpack-dev-server
    
  3. Isa Bootstrap. Iye zvino tinogona kuisa Bootstrap. Tichaisawo Popper sezvo kudonhedza kwedu, mapopovers, uye maturusi ezvishandiso zvinoenderana nazvo pazvinzvimbo zvavo. Kana iwe usingaronge kushandisa izvo zvikamu, unogona kusiya Popper pano.

    npm i --save bootstrap @popperjs/core
    
  4. Isa zvimwe zvinotsamira. Pamusoro peWebpack neBootstrap, isu tinoda zvimwe zvishoma zvinotsamira kuti titore zvakanaka uye kuunganidza Bootstrap's CSS uye JS ine Webpack. Izvi zvinosanganisira Sass, mamwe maloaders, uye Autoprefixer.

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

Iye zvino zvatine zvese zvinodiwa zvinomisikidzwa, tinogona kusvika kubasa kugadzira mafaera eprojekiti uye kupinza Bootstrap.

Chirongwa cheprojekiti

Isu takatogadzira my-projectfolda uye takatanga npm. Iye zvino tichagadzirawo edu srcuye distmaforodha ekutenderedza chimiro cheprojekiti. Mhanya zvinotevera kubva my-project, kana nemaoko gadzira iyo folda uye faira chimiro chinoratidzwa pazasi.

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

Kana wapedza, chirongwa chako chakazara chinofanira kutaridzika seizvi:

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

Panguva ino, zvese zviri munzvimbo chaiyo, asi Webpack haishande nekuti isu hatisati tazadza zvedu webpack.config.js.

Gadzirisa Webpack

Nekutsamira kwakaiswa uye yedu purojekiti folda yakagadzirira kuti isu titange kukodha, isu tinokwanisa ikozvino kugadzirisa Webpack uye kumhanyisa chirongwa chedu munharaunda.

  1. Vhura webpack.config.jsmupepeti wako. Sezvo isina chinhu, isu tichada kuwedzera imwe boilerplate config kwairi kuti tikwanise kutanga server yedu. Ichi chikamu chegadziriso chinoudza Webpack yaifanira kutsvaga JavaScript yepurojekiti yedu, kwainoburitsa kodhi yakaunganidzwa ku ( dist), uye kuti sevha yekuvandudza inofanirwa kuita sei (kudhonza kubva distpafolda nekupisa kurodha).

    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. Tevere tinozadza yedu dist/index.html. Iyi ndiyo HTML peji Webpack inozorodha mubrowser kuti ishandise mabundled CSS uye JS isu tichawedzera kwairi mumatanho anotevera. Tisati taita izvozvo, isu tinofanirwa kuzvipa chimwe chinhu chekupa uye nekubatanidza iyo outputJS kubva padanho rakapfuura.

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

    Isu tiri kusanganisira zvishoma zveBootstrap styling pano neiyo div class="container"uye <button>kuti isu tione kana Bootstrap's CSS inotakurwa neWebpack.

  3. Iye zvino isu tinoda npm script kumhanya Webpack. Vhura package.jsonuye wedzera startscript inoratidzwa pazasi (iwe unofanirwa kunge watova nebvunzo script). Tichashandisa chinyorwa ichi kutanga yedu yemuno Webpack dev server.

    {
      // ...
      "scripts": {
        "start": "webpack serve --mode development",
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      // ...
    }
    
  4. Uye pakupedzisira, tinogona kutanga Webpack. Kubva pane my-projectfolda mune yako terminal, mhanyisa iyo ichangobva kuwedzerwa npm script:

    npm start
    
    Webpack dev server iri kushanda

Muchikamu chinotevera uye chekupedzisira chegwaro iri, isu tichamisa maWebpack loaders uye kuunza ese eBootstrap's CSS neJavaScript.

Ngenisa Bootstrap

Kupinza Bootstrap muWebpack kunoda maloaders atakaisa muchikamu chekutanga. Isu takavaisa nenpm, asi ikozvino Webpack inoda kugadzirwa kuti ishandise.

  1. Gadzirisa maloaders mu webpack.config.js. Yako faira yekumisikidza ikozvino yakwana uye inofanirwa kufanana nesnippet iri pazasi. Chikamu chitsva chete pano ndicho modulechikamu.

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

    Heino kudzokorora kwechikonzero nei tichida ese aya anorodha. style-loaderinopinza iyo CSS muchimwe <style>chinhu mune <head>iyo HTML peji, css-loaderinobatsira nekushandisa @importuye url(), postcss-loaderinodiwa kune Autoprefixer, uye inotibvumira sass-loaderkushandisa Sass.

  2. Zvino, ngatitorei kunze Bootstrap's CSS. Wedzera zvinotevera src/scss/styles.scsskuunza kunze kweBootstrap's source Sass.

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

    Iwe unogona zvakare kuunza edu masitayera ega kana uchida. Verenga yedu Sass import docs kuti uwane ruzivo.

  3. Tevere tinoisa iyo CSS uye tinopinza Bootstrap's JavaScript. Wedzera zvinotevera src/js/main.jskurodha iyo CSS uye pinza yese yeBootstrap's JS. Popper ichaendeswa kunze kwenyika kuburikidza neBootstrap.

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

    Iwe unogona zvakare kupinza JavaScript plugins mumwe nemumwe sezvinodiwa kuti uchengetedze saizi dzemasumbu pasi:

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

    Verenga yedu JavaScript docs kuti uwane rumwe ruzivo nezve mashandisiro eBootstrap's plugins.

  4. Uye wapedza! 🎉 NeBootstrap 's sosi Sass uye JS yakazara yakazara, yako yenzvimbo yekuvandudza sevha inofanirwa kutaridzika seizvi.

    Webpack dev server inoshanda neBootstrap

    Iye zvino unogona kutanga kuwedzera chero zvinhu zveBootstrap zvaunoda kushandisa. Ita shuwa yekutarisa yakazara Webpack muenzaniso purojekiti yekuti ungabatanidza sei yakawedzera tsika Sass uye kukwidziridza kuvaka kwako nekupinza chete zvikamu zveBootstrap's CSS uye JS yaunoda.

Production optimizations

Zvichienderana nekuseta kwako, ungangoda kuita imwe chengetedzo uye nekumhanyisa optimizations inobatsira pakumhanyisa chirongwa mukugadzira. Ziva kuti izvi optimizations hazvina kushandiswa paWebpack muenzaniso purojekiti uye zviri kwauri kuti uite.

Kubvisa CSS

Iyo style-loaderyatakagadzirisa pamusoro inoburitsa CSS mubundle kuitira kuti kurodha nemaoko CSS faira mukati dist/index.htmlhazvidiwi. Iyi nzira inogona kusashanda neyakaomesesa Content Security Policy, zvisinei, uye inogona kuve bhodhoro mukushandisa kwako nekuda kwehukuru hukuru.

Kupatsanura iyo CSS kuti isu tigone kuiisa zvakananga kubva dist/index.html, shandisa iyo mini-css-extract-loaderWebpack plugin.

Kutanga, isa iyo plugin:

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

Wobva wasimbisa uye shandisa iyo plugin muWebpack kumisikidza:

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

Mushure mekumhanya npm run buildzvakare, pachave nefaira nyowani dist/main.css, iyo ichange iine ese eCSS anounzwa kunze kwenyika ne src/js/main.js. Kana iwe ukatarisa dist/index.htmlmubrowser yako izvozvi, maitiro acho anenge asipo, sezvazviri iye zvino mu dist/main.css. Iwe unogona kusanganisira iyo yakagadzirwa CSS mune dist/index.htmlseizvi:

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

Kutora mafaira eSVG

Bootstrap's CSS inosanganisira akawanda mareferensi kuSVG mafaera kuburikidza neinline data:URIs. Kana iwe ukatsanangura Content Security Policy yepurojekiti yako data:inovharira maURI emifananidzo, saka aya mafaera eSVG haazotakuri. Iwe unogona kutenderedza dambudziko iri nekubvisa iyo inline SVG mafaera uchishandisa Webpack's asset modules chimiro.

Gadzirisa Webpack kuti ubvise inline SVG mafaera seizvi:

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

Mushure mekumhanya npm run buildzvakare, iwe unowana iyo SVG mafaera akatorwa mukati dist/iconsuye nemazvo anonongedzwa kubva kuCSS.


Unoona chimwe chinhu chisina kunaka kana chekare pano? Ndokumbira uvhure nyaya paGitHub . Unoda rubatsiro kugadzirisa dambudziko? Tsvaga kana tanga nhaurirano paGitHub.