Snap.svg
Snap.svg copied to clipboard
Es6 import error
When i'm trying to import snapsvg like this
import Snap from 'snapsvg'
I'm getting such error:
Uncaught TypeError: Cannot read property 'on' of undefined
I'm not using webpack, that's why solutions with loaders from this issue not working for me.
Where you able to solve this error? I'm having the same error.
Nope :confused:
For everyone who has this problem, I found out that there is a commonjs snapsvg-package available on npm. https://www.npmjs.com/package/snapsvg-cjs
Following the grunt install of it worked for me, along with using npm install import-loaders
and doing import Snap from 'imports-loader?this=>window,fix=>module.exports=0!snapsvg/dist/snap.svg.js'
.
I also used the npm install snapsvg-cjs
and that worked too.
The problem with https://www.npmjs.com/package/snapsvg-cjs is that it’s on 0.4.0
, not the current version, 0.5.1
. I was using snapsvg-cjs for a little while, but hit one of the bugs that was fixed in 0.4.1
I’ve opened up a PR suggesting some README changes. Here’s a summary:
webpack
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';
Webpack config fix worked for me, with corrections to the above:
resolve {
should be resolve: {
snapsvg: '/snapsvg/dist/snap.svg.js'
should be snapsvg: 'snapsvg/dist/snap.svg.js'
@ryascl Ah! Good catch. Updated my snippet.
I was pasting out of a long, complicated production webpack config I got it working in, and manually typed part of it (wrongly).
Is this resolved? I would love to use snap in a framer module, which is coffeescript, however this would mean I need some kind of export.
@lukasoppermann I don’t have Framer experience so I don’t know what the importing experience looks like. No, Snap doesn't have any exports—that would require a change to the library. I simply updated the existing config hack for webpack, which I don’t think would work for something like Framer.
The main problem is this lib predates CJS/ES6 modules, so it’d be more involved than just adding export default Snap
to the end of the file. Lots of gross window
scopes and stuff.
Thank you @dangodev, your snippet is the way! Perfectly working with Webpack 4.10.2 and Snap 0.5.1!
I had eve is not defined
as well... I tested the i-dont-understand-why-it-is-so-complicated-to-import modules fix from @dangodev but nothing. I ended up with the suggestion of @hipkiss91 with npm install snapsvg-cjs
and it works like a charm. Even if it's CommonJS and it's pretty ugly not to have a correct import, it works...
See fix for Webpack 4.x with Imports Loader 1.x https://github.com/adobe-webplatform/Snap.svg/issues/639