How do I create a custom webpack loader that still compiles my react code properly?

526 views Asked by At

I'm trying to build a custom loader to use in my NWB React project. I'd just like to create a custom loader that does nothing, but maintains the proper compilation for my react components. I can't seem to get the loaders to run in the proper order, namely my custom loader should happen first and then the source code should be compiled.

I've successfully gotten a loader to run and I've tried setting it as a preloader in the config. I've also tried manually adding a second pass of the babel-loader, but while it has changed the compiled code, it's still not compiling the react component properly.

Here's my nwb.config.js:

module.exports = function({command}) {

  /* Set config */
  let config = {
    type: 'react-app',
  }

  config.webpack = {
    entry: {
      App: './src/components/App.js',
    }
    extra: {
      output: {
        path: path.resolve('./dist/webpack_bundles/'),
      },
      module: {
        rules: [
          {
            test: /\.js$/,
            exclude: /node_modules/,
            loader: path.resolve('./my-loader.js'),
            enforce: 'pre',
            options: {text: 'hello world'},
          }
        ]
      },
    },
  }
  return config
}

And here's the text of my loader, mostly borrowed from an example on webpack:

export default function(source) {
  // Do nothing
  return `export default ${ JSON.stringify(source) }`;
}

Finally, here is the source that I'm using:

import React, {Component} from 'react'

export default class App extends Component {
  render() {
    return <div className="App">
      <p>Hello World</p>
    </div>
  }
}

When I remove the module section from my webpack config, nwb's default webpack config properly compiled my react component. However, when I insert my loader, it no longer compiles it properly. It simply return the react code unchanged. I'd like it to compile the code returned by my loader.

1

There are 1 answers

0
Jake Klingensmith On

I just needed to return the source without stringifying it:

export default function(source) {
  // Do nothing
  return source;
}