This shows how to call into a JavaScript library in Blazor. Also it includes how to set up webpack and the build to work with visual studio so the JS library gets compiled and bundled on build
Adapted from:
Using npm packages with Blazor
Create a new folder in the project, for example "npm_packages"
Open a terminal and cd into the new "npm_packages" directory
Run the following to initialize the folder as an npm package:
npm init
Install the library, for example moment.js
npm install --save moment
Install webpack and the webpack cli
npm install --save webpack webpack-cli
Install babel
npm intall --save-dev babel-loader @babel/core
Now in our npm_packages directory create a webpack.config.js like this:
const path = require("path");
module.exports = {
module: {
rules: [
{
test: /\\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
}
]
},
output: {
path: path.resolve(__dirname, '../wwwroot/js'), //points to the wwwroot folder in the parent blazor project
filename: "my_lib.js", // Configurable to whatever name you would like
library: "MyLib" //Configurable to whatever library name you want
}
};
Now add a build command to your package.json that looks like this:
"build": "webpack --mode production"
Add a src folder to your npm_packages folder and then add an index.js file to that folder:
import { getCurrentTime } from './timeLib';
export function GetCurrentTime() {
return getCurrentTime();
}
As well as the file we will use to interop with c# called timeLib.js (imported above):