Developing for Splunk Enterprise

Splunk App with React UI, Webpack and SplunkJS stack

Stjubit
Explorer

Hi, I want to create a Splunk app that displays custom searches I get from the SplunkJS stack in a React UI component.

I got the React UI working, but I still have issues importing the SplunkJS modules. I'm using Babel for source code compilation and Webpack for bundling my assets.

The SplunkJS stack modules are initialized in the browser at runtime and I want to use those already initialized modules so that I don't have to bother with login, permissions, etc.. Adding the SplunkJS SDK as module is not an option.

Basically, I'm trying to use the utils module like that:

 

require(["splunkjs/mvc/utils"], function(utils) {
  console.log(utils.getCurrentApp());
});

 

 

This code would generate an error in Webpack, because the module 'splunkjs/mvc/utils' is not defined/found of course. The module only exists on the Splunk appserver and I want webpack to ignore the import of this module at build time. So I thought that the externals configuration option in the webpack config is exacly what I'm looking for:

 

module.exports = {
  ...
  externals: {
      "splunkjs/mvc/utils": "commonjs2 splunkjs/mvc/utils",
  },
  ...
}

 

 

Webpack is now able to generate the bundle without build errors, because it completely ignores the SplunkJS module:

 

[splunkjs/mvc/utils] external "splunkjs/mvc/utils" 42 bytes {sirp-dashboard} [built]

 

 

That's totally what I wanted, but I receive the following error when executing the app:

 

Error: Module name "splunkjs/mvc/utils" has not been loaded yet for context: _. Use require([])

 

 

It looks like the splunkjs module is loaded after the bundle JS code is executed. I can execute the same code in the dev console as soon as the browser finished loading the page:

grafik.png

I also tried to use different externals types in the webpack config like 'amd', 'umd', ... . They produce a different error:

 

ReferenceError: __WEBPACK_EXTERNAL_MODULE_splunkjs_mvc_utils__ is not defined

 

 

Is there a way to make webpack and the SplunkJS stack work? Any solution/hint is greatly appreciated 🙂

 

home-search.js (my react component)

 

import React, { Component } from 'react';

export default class HomeSearch extends Component {

  render() {
    require(["splunkjs/mvc/utils"], function(utils) {
      console.log(utils.getCurrentApp());
    });

    return (
      <div>
        
      </div>
    )
  }
}

 

 

webpack.config.js

 

const path = require('path');
const fs = require('fs');
const appConfig = require('./appConfig');

const srcDir = path.join(__dirname, 'src');
const pages = fs.readdirSync(path.join(srcDir, 'pages')).reduce((entries, name) => {
  // eslint-disable-next-line no-param-reassign
  entries[name] = path.join(srcDir, 'pages', name, 'index.jsx');
  return entries;
}, {});

const jsBuildDir = path.join(__dirname, 'build', appConfig.id, 'appserver', 'static', 'build');

module.exports = {
  mode: process.env.NODE_ENV !== 'production' ? 'development' : 'production',
  entry: pages,
  externals: {
      "splunkjs/mvc/utils": "commonjs2 splunkjs/mvc/utils",
  },
  output: {
    path: jsBuildDir,
  },
  resolve: {
    extensions: ['.js', '.jsx'],
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        use: ['babel-loader'],
      },
      {
        test: /\.css$/i,
        use: ['style-loader', 'css-loader'],
      },
      {
        test: /\.txt$/,
        use: ['raw-loader'],
      },
      {
        test: /\.(png|jpg|jpeg|gif|svg|woff|woff2)$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              name: '[hash].[ext]',
              limit: 100000,
            },
          },
        ],
      },
      {
        test: /\.(eot|ttf|wav|mp3)$/,
        use: [
          {
            loader: 'file-loader',
            options: {
              name: '[hash].[ext]',
            },
          },
        ],
      },
    ],
  },
};

 

 

~ Julian

Labels (2)
0 Karma

mleati
Engager

I am interested in this issue too. I followed the instructions for building a ReactJS based UI provided at .conf19.  One of the presentations I used was DEV2165 (Deep Dive on The New Dashboarding and Content Export Experience). I am trying to use ReactJS for building a Splunk app. It defines a React component that hosts a Dashboard (using @splunk/dashboard-* modules) and other React components. 

My first observation is that Splunk basically stopped publishing any materials/documentations on this subject after .conf19. The documentation is severely lacking. It is not clear if Splunk is committed to making this technique (ReactJS) available to the customers.

That said, I was able to implement a dashboard using the techniques described in the the aforementioned presentation. Next step for me is to integrate custom React-based UI with the dashboard. I tried using Splunk JS just like Stjubit. I did not get as far as Julian did though (my experience with React/WebPack and web development in general is rather limited). Presentation slides say this about the issue:

Other Advanced Use Cases

Token, namespaces, filters
• Similar to how they work in SimpleXML
Event handlers
• Create and register event handlers triggered by keyboard, mouse or other events
• Example: drilldown to url
Theming
• Dark theme

Basically that's all I was able to find about it. And it does not work. From my experience so far with this new ReactJS based library, it appears that the best case scenario is going to be that the Dashboard customization opportunities are going to be as limited as they were with SplunkJS, which makes me think about using ReactJS without the Splunk's Dashboard components and relying on a third party visualization library instead. I would still need to figure out how to perform Splunk searches for this app (in the context of a Splunk app).

 

It is not clear if the legacy SplunkJS is supposed to be used with ReactJS or there is/will be a new API for that. I noticed that Splunk added a new module (splunk-sdk-js) to NPM repository two days ago. Could this be something that we might use? NPM refused to install it for me though.

0 Karma

Stjubit
Explorer

Yep I totally understand the struggle. I was able to use the npm packages by looking at the source code, which is a bit of a pain, because it is compiled and bundled javascript code. I have a meeting with the Splunk PM responsible for the new dashboard framework on Monday to talk about the current status.

 

However, I can give you some hints to start:

1) Join the Splunk Slack User Group and the channels #appdev + #webplatform. My name in the Slack channel is "Julian" and I have a dwarf with a Splunk logo as avatar.

2) You don't have to "require" the splunkjs module in your JSX files, because it's already initialized in the browser at runtime. Just use it like the following snippet without import/require logic. Webpack will ignore that splunkjs does not exist.

var service = splunkjs.mvc.createService({ owner: "nobody" });

You could also import the React framework from CDN and then use Babel to compile the JSX code. Then you can require splunkjs.

3) Use the following project to start out:

https://github.com/splunk/dashboard-conf19-examples

4) Install the React Developer Tools addon in your browser and check out the React components of other apps.

5) Have a look at the Splunk Dashboards Beta App in Splunkbase.

6) You can use @splunk/search-job for simple searches

7) Check out all @splunk packages on npmjs.com and what they do. The documentation is bad af, but better than nothing.

😎 Search for code samples on Github with the advanced code search feature like "@splunk/react-ui/Button". You will find about 5 repos that use the Splunk React UI and you can have a look at them to see how everything works.

 

The whole new framework is still in beta and absolutely noone is using it at the moment. Keep that in mind. However, React is cool and I wanted to use it. So I wasted two weeks for that lol.

mleati
Engager

Thanks a lot for sharing. I did most of the things you mentioned. However points 1 and 2 are invaluable. I just joined the Slack group (and now I have to learn Slack in addition to everything else :-). I am going to research what's there and proceed with my project.

0 Karma
Take the 2021 Splunk Career Survey

Help us learn about how Splunk has
impacted your career by taking the 2021 Splunk Career Survey.

Earn $50 in Amazon cash!