4

I'm using require and webpack on a project and want to use snapsvg but when I include it I get the error:

Uncaught TypeError: Cannot read property 'on' of undefined

Code is:

var Snap = require('snapsvg');
SVG = Snap('#svg');
James
  • 131
  • 1
  • 8
  • Please add some code to your question so that we can help to identify the problem. – Rob Murray Mar 30 '16 at 09:26
  • 1
    @R.Murray I've added the code used when I get the error but it's the use of require that seems to cause the issue. – James Mar 30 '16 at 12:51

3 Answers3

9

Ah the way to do it is to add:

var webpack = require('webpack');
module.exports = {
  ...
  module: {
    loaders: [{
      test: require.resolve('snapsvg'),
      loader: 'imports-loader?this=>window,fix=>module.exports=0'
    }]
  }
  ...
};

in webpack.config.js using imports-loader

James
  • 131
  • 1
  • 8
  • For those ending up here, [here](https://github.com/adobe-webplatform/Snap.svg/issues/639) is a fix that works with Webpack 5 and Imports loader 3. – Bubbler Apr 05 '22 at 10:04
4

You can also use snapsvg-cjs, which is actually wrapper writter in snapsvg with common js.

Steps:

npm install snapsvg-cjs

Import in component like below:-

import "snapsvg-cjs";

declare const Snap: any;

Now you have Snap object.

Sagar Kharche
  • 2,577
  • 2
  • 24
  • 34
1

To load with webpack 2.x and 3.x, install Imports Loader (npm i -D imports-loader), and add the following to your webpack config:

module: {
  rules: [
    {
      test: require.resolve('snapsvg/dist/snap.svg.js'),
      use: 'imports-loader?this=>window,fix=>module.exports=0',
    },
  ],
},
resolve: {
  alias: {
    snapsvg: 'snapsvg/dist/snap.svg.js',
  },
},

Then, in any module you’d like to require Snap, use:

import Snap from 'snapsvg';

SRC: SnapSVG GitHub

Yogi
  • 1,527
  • 15
  • 21
  • I have been using the above for years, without issues. Has anyone got an update for Webpack 4 and imports-loader v1.2? – Hawkeye64 Nov 16 '20 at 20:57