Using tether with webpack (Angular CLI)

4.6k Views Asked by At

I'm developing a project using Angular CLI. So I installed tether using npm install tether --save, and imported the depedency in app.component.ts using import * as Tether from 'tether'.

When I try to initialize Tether with new Tether({ ... }) it prints the following error in the console:

EXCEPTION: WEBPACK_IMPORTED_MODULE_4_tether is not a constructor

If I print the Tether variable using console.log(Tether) it gives me what is seems an empty object.

Could you guys help me? I've never used neither typescript nor webpack before, so I'm sorry if I'm missing something obvious here.

3

There are 3 best solutions below

6
On

Use import Tether from 'tether'; This imports the default export of tether which happens to be the TetherClass you're trying in instantiate.

The code import * as Tether imports all (default and named) exports of the library, and you'd need to new Tether.TetherClass().

Check out the great Exploring ES6 book on modules for details.

0
On

If you are using bootstrap4 then tether.js is already a dependency. This might work

Using Angular-cli

First, install Bootstrap from npm:

npm install bootstrap@next

Then add the needed script files to angular-cli.json --> scripts:



 "scripts": [
          "../node_modules/jquery/dist/jquery.js",
          "../node_modules/tether/dist/js/tether.js",
          "../node_modules/bootstrap/dist/js/bootstrap.js"
           ],

Finally add the Bootstrap CSS to the angular-cli.json --> styles array:

    "styles": [
  "../node_modules/bootstrap/dist/css/bootstrap.css",
  "styles.css"`enter code here`
],

Restart ng serve if you're running it, and Bootstrap 4 should be working on your app.

For Webpack

If you are using webpack:

Set up bootstrap-loader as described in docs;

Install tether.js via npm;

Add tether.js to the webpack ProvidePlugin plugin:

 plugins: [
        <... your plugins here>,
        new webpack.ProvidePlugin({
            $: "jquery",
            jQuery: "jquery",
            "window.jQuery": "jquery",
            "window.Tether": 'tether'
        })
    ]

Bootstrap 4 is no longer using tag window.tether

Note that using Bootstrap 4.0.0-alpha.6,

Bootstrap is no longer checking for "window.Tether" but the global variable "Tether", so the webpack configuration becomes

plugins: [
    <... your plugins here>,
    new webpack.ProvidePlugin({
        $: "jquery",
        jQuery: "jquery",
        "window.jQuery": "jquery",
        "Tether": 'tether'
    })
]
0
On

Since you are using Angular-cli, you'll have to add that to your angular-cli.json

In your file(angular-cli.json) include it under the scripts array:

 "scripts": [
            "other/scripts/you've used"
            "../node_modules/tether/dist/js/tether.min.js",
            "../node_modules/tether-shepherd/dist/js/shepherd.min.js"
        ],

Include the css in styles.

Hope this works out.