admin管理员组

文章数量:1389903

According to Bootstrap 5 official documentation, we can import pre-piled js files from bootstrap/js/dist and build a custom bundle using (Webpack, rollup, ...).

.0/getting-started/javascript/#individual-or-piled

And in the optimizing section in docs, they gave an example of how you can import js files. .0/customize/optimize/#lean-javascript

The problem: I created a file named bootstrap.js

import 'bootstrap/js/dist/tooltip';

and I want only to use the Tooltip plugin. I use the below configuration for rollup

  const plugins = [
    babel({
      exclude: 'node_modules/**',
      // Include the helpers in each file, at most one copy of each
      babelHelpers: 'bundled',
      presets: [
        [
          '@babel/preset-env',
          {
            loose: true,
            bugfixes: true,
            modules: false
          }
        ]
      ]
    }),
    nodeResolve()
  ]

  const bundle = await rollup.rollup({
    input: './js/vendors/bootstrap.js',
    plugins,
  })

  await bundle.write({
    format: 'umd',
    file: './file.js'
  })

After generating the file.js and use an HTML page an error shows up in the console file.js:1727 Uncaught ReferenceError: process is not defined

Also I can't use bootstrap syntax to initialize the Tooltip plugin new bootstrap.Tooltip gives an error of undefined bootstrap.

I can achieve what I want by import these files from js/src folder and export them as they use in js/src/index.umd.js but following bootstrap official documentation on how to import their plugin seems not to work properly.

According to Bootstrap 5 official documentation, we can import pre-piled js files from bootstrap/js/dist and build a custom bundle using (Webpack, rollup, ...).

https://getbootstrap./docs/5.0/getting-started/javascript/#individual-or-piled

And in the optimizing section in docs, they gave an example of how you can import js files. https://getbootstrap./docs/5.0/customize/optimize/#lean-javascript

The problem: I created a file named bootstrap.js

import 'bootstrap/js/dist/tooltip';

and I want only to use the Tooltip plugin. I use the below configuration for rollup

  const plugins = [
    babel({
      exclude: 'node_modules/**',
      // Include the helpers in each file, at most one copy of each
      babelHelpers: 'bundled',
      presets: [
        [
          '@babel/preset-env',
          {
            loose: true,
            bugfixes: true,
            modules: false
          }
        ]
      ]
    }),
    nodeResolve()
  ]

  const bundle = await rollup.rollup({
    input: './js/vendors/bootstrap.js',
    plugins,
  })

  await bundle.write({
    format: 'umd',
    file: './file.js'
  })

After generating the file.js and use an HTML page an error shows up in the console file.js:1727 Uncaught ReferenceError: process is not defined

Also I can't use bootstrap syntax to initialize the Tooltip plugin new bootstrap.Tooltip gives an error of undefined bootstrap.

I can achieve what I want by import these files from js/src folder and export them as they use in js/src/index.umd.js but following bootstrap official documentation on how to import their plugin seems not to work properly.

Share Improve this question edited Apr 18, 2021 at 23:43 Mourad Karoudi asked Apr 16, 2021 at 17:46 Mourad KaroudiMourad Karoudi 3884 silver badges13 bronze badges 1
  • 1 I suspect that your problem isn't specific to bootstrap, and has more to do with the rollup config not being set up for a browser. For example, nodeResolve should be configured with browser: true npmjs./package/@rollup/plugin-node-resolve. Likewise, you should check your babel config. If you need more help, consider sharing a more plete example. – murrayju Commented Apr 24, 2021 at 0:21
Add a ment  | 

2 Answers 2

Reset to default 3

Documentation error

While this is not the answer you want, it does seem that the correct answer is, "Bootstrap's documentation has an error."

For umd output, if I import with this syntax:

import Dropdown from '../../node_modules/bootstrap/js/dist/dropdown';

the build fails with the following error:

Error: 'default' is not exported by node_modules\bootstrap\js\dist\dropdown.js, imported by src\js\bootstrap-build.js

Which is contrary to this: Files in bootstrap/js/dist use the default export,.

What does work (includes Popper):

To the reader, assuming you came here to find a solution to a build problem you are having, below is what works for me.

This answer assumes all dependencies were installed using NPM as a dev dependency except for Bootstrap 5, which was installed with this mand:

npm install bootstrap

This is rollup.config.js:

import {terser} from 'rollup-plugin-terser';

export default {
    input: './src/js/bootstrap-build.js',
    output: {
        file: 'dist/js/bootstrap.umd.min.js',
        format: "umd",
        name: "bsbundle", // this is the name of the global object
        esModule: false,
        sourcemap: true,
    },
    plugins: [terser({press: {drop_console: true, module: true}})]
};

This is the project's entry script, i.e. bootstrap-build.js, located in <project root>/src/js/:

import * as Popper from '../../node_modules/@popperjs/core/dist/umd/popper.js';

// from 'js/src/*' source which works
import Modal from '../../node_modules/bootstrap/js/src/modal';
import Tab from '../../node_modules/bootstrap/js/src/tab';
import Dropdown from '../../node_modules/bootstrap/js/src/dropdown';
import Tooltip from '../../node_modules/bootstrap/js/src/tooltip';

export default {
  // Alert,
  // Button,
  // Carousel,
  // Collapse,
  Dropdown,
  Modal,
  // Offcanvas,
  // Popover,
  // ScrollSpy,
  Tab,
  // Toast,
    // Popper,
  Tooltip
}

And the package.json:

{
  "name": "bsponents",
  "version": "1.0.0",
  "description": "Project for building Bootstrap 5 ponents.",
  "main": "index.js",
  "scripts": {
    "build-bs": "rollup -c"
    },
  "keywords": [],
  "author": "",
  "license": "",
  "dependencies": {
    "bootstrap": "^5.1.3"
  },
  "devDependencies": {
    "@rollup/plugin-multi-entry": "^4.1.0",
    "autoprefixer": "^10.4.0",
    "cross-env": "^7.0.3",
    "postcss": "^8.3.11",
    "rollup": "^2.60.0",
    "rollup-plugin-node-resolve": "^5.2.0",
    "rollup-plugin-terser": "^7.0.2",
  }
}

NPM build mand:

NPM run build-bs

Build note: The line importing Popper in the Bootstrap Dropdown and Tooltip source files is mented out.

Bundle includes Popper, Dropdown, Modal, Tab, and Tooltip

File index.html in project root for testing bundle.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Bootstrap 5 ponents</title>
    <!-- custom Bootstrap bundle saves about 21kb -->

    <link rel="stylesheet" href="./node_modules/bootstrap/dist/css/bootstrap-reboot.min.css">
    <link rel="stylesheet" href="./node_modules/bootstrap/dist/css/bootstrap.min.css">

    <!-- and a few simple styles -->
    <style>
        body {
            padding: 5rem;
            margin: 1rem auto;
        }

        .btn-wrapper {
            display: inline-block;
            margin: 1rem auto;
        }

        .btn-wrapper li {
            padding: 1rem
        }

        .tab-pane {
            padding: 2rem;
        }

        ul {
            margin: 3rem
        }
    </style>

</head>

<body>


    <h1>Bootstrap 5 ponents</h1>

    <ul>
        <li>Dropdown</li>
        <li>Modal (an option in the dropdown)</li>
        <li>Tabs</li>
        <li>Tooltip</li>
    </ul>

    <div class="btn-wrapper dropdown" data-bs-toggle="tooltip" data-bs-placement="top" title="This is a Bootstrap 5 dropdown.">
        <button type="button" id="btnDropDown" class="btn btn-primary btn-calculator dropdown-toggle" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="true">Options&nbsp;<span class="caret"></span>
        </button>
        <ul class="dropdown-menu" aria-labelledby="btnDropDown">
            <li data-bs-toggle="modal" data-bs-target="#MYMODAL">
                <b>Modal</b>
            </li>
            <li>
                Second option
            </li>
            <li>
                And a final option
            </li>
        </ul>
    </div>

    <div>

        <nav>
            <div class="nav nav-tabs" id="nav-tab" role="tablist">
                <button class="nav-link active" id="nav-tab-1" data-bs-toggle="tab" data-bs-target="#nav-calc-1" type="button" role="tab" aria-controls="nav-calc-1" aria-selected="true">Tab 1</button>
                <button class="nav-link" id="nav-tab-2" data-bs-toggle="tab" data-bs-target="#nav-options-1" type="button" role="tab" aria-controls="nav-options-1" aria-selected="false">Tab 2</button>
            </div>
        </nav>

        <!-- Tab panes -->
        <div class="tab-content" id="nav-tabContent-1">
            <div class="tab-pane fade show active" id="nav-calc-1" role="tabpanel" aria-labelledby="nav-tab-1">
                <p>tab 1</p>
            </div>
            <!--role="tabpanel"-->

            <div class="tab-pane fade show" id="nav-options-1" role="tabpanel" aria-labelledby="nav-tab-2">
                <!-- option tab content -->
                <p>tab 2</p>

            </div>
            <!-- role tabpanel -->

        </div>
        <!--end tab-content-->

    </div>


    <!-- modal -->
    <div class="modal fade" tabindex="-1" id="MYMODAL">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Modal title</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>Before you leave, hover over the below buttons.</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal" data-bs-toggle="tooltip" data-bs-placement="bottom" title="Click to close">Seconday</button>
                    <button type="button" class="btn btn-primary" data-bs-toggle="tooltip" data-bs-placement="right" title="I do nothing!">Primary</button>
                </div>
            </div>
        </div>
    </div>

    <!-- end modal -->


    <script src="./dist/js/bootstrap.umd.min.js"></script>
    <script>
        var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
        var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
            return new bsbundle.Tooltip(tooltipTriggerEl)
        })
    </script>
</body>

</html>

Development environment:

  • Windows 10
  • Rollup v2.6
  • Node v16.10.0
  • NPM 8.1.3
  • Bootstrap 5.1.3

Build run in VS Code v1.62's Bash terminal.

The result:

The build bundle including Popper, <project root>/dist/js/bootstrap.umd.min.js, saves about 21kb over Bootstrap's distributed minified bundle.

Probable documentation issue reported on GitHub

Not sure how to dissect your code - you're missing the whole dependance on Popper.

But this is how I would have done it (hint: I took the BS5 source code and stripped all the things not wanted.)

Assuming you're piling on top of a fork of Boorstrap 5:

File: build\rollup.config.mk.js:

'use strict'

const path = require('path')
const { babel } = require('@rollup/plugin-babel')
const { nodeResolve } = require('@rollup/plugin-node-resolve')
const replace = require('@rollup/plugin-replace')
const banner = require('./banner.js')

let fileDest = `bootstrap-mk`
const external = ['@popperjs/core']
const plugins = [
  babel({
    // Only transpile our source code
    exclude: 'node_modules/**',
    // Include the helpers in the bundle, at most one copy of each
    babelHelpers: 'bundled'
  })
]
const globals = {
  '@popperjs/core': 'Popper'
}

const rollupConfig = {
  input: path.resolve(__dirname, `../js/index.mk.umd.js`),
  output: {
    banner,
    file: path.resolve(__dirname, `../dist/js/${fileDest}.js`),
    format: 'umd',
    globals
  },
  external,
  plugins
}

rollupConfig.output.name = 'bootstrap'

module.exports = rollupConfig

... and also ...

File: js\index.mk.umd.js

import Tooltip from './src/tooltip'

export default {
  Tooltip
}

Then call: rollup --config build/rollup.config.mk.js --sourcemap from the mand line, or add something like this to the packacge.json \ "scripts" section:

  "js-pile-mk": "rollup --config build/rollup.config.mk.js --sourcemap",

... and call npm run js-pile-mk from the mand line.

Output will be a file called: dist\js\bootstrap-mk.js (and a map file)


If you want to not use a fork, but rather a node_modules sub-folder, then go about changing the paths in the build\rollup.config.mk.js file.

本文标签: javascriptHow to build custom bootstrap bundle using RollupStack Overflow