Search code examples
webpackloaderwebpack-loader

How to use 'import' statements in custom webpack loader


I am trying to build a custom webpack loader (to import everything specified in my json file).

My first step was to copy some sample loader (I chose file-loader) and register it as my custom loader (in webpack.config.js):

rules: [{
    test: /\.(png|svg|jpg|gif)$/,
    use: [ { loader: path.resolve('asset-loader/index.js'), options: { } } ]
  },{

The loader gets picked up correctly, but I get an error at the first statement in the loader:

import path from 'path';

Through some experimentation I found out that it can't comprehend ES6 import syntax but instead expects "require('path').

Why is that? As I said, I copied the file-loader from github - which works just fine.

Is there a way to configure webpack to be able to work with the import statements?


Solution

  • You can't use esm syntax because node does not allow that YET. You have to parse it to cjs to be able to be interpreted by node.

    Why it works with file-loader? Because, as you can see here, the distributed file is compiled/transpiled.