Search code examples
javascriptwebpackwebpack-2

Webpack fast import rule


I need to use webpack with snapsvg. According to snapsvg's documentation, to import it with webpack, I need to use a loader:

const Snap = require(`imports-loader?this=>window,fix=>module.exports=0!snapsvg/dist/snap.svg.js`);

So, in every Javascript file I use, I need to write this thing. I would like to avoid it.

Aliased import

Is there a way, maybe in webpack.config.js, to specify that every time this is encoutered:

import snap from "snapsvg"

Then that line is translated into the one mentioned before? So I can avoid typing the same thing in every file.


Solution

  • You can use this rule:

    Install Imports Loader (npm i -D imports-loader) and add this 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',
      },
    },
    

    With that you can import snap from "snapsvg" without hassle.