Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load javascript in webpack

I am new to javascript dev in general and webpack in particular. I want to use this chess board module (https://github.com/oakmac/chessboardjs/) in my project. It sees to be exporting ChessBoard object. My project is using ES6, so I would love to be able to

import { ChessBoard } from 'chessboard'

or

import ChessBoard from 'chessboard'

I understand that I need some sort of loader for this. I have tried to add expose loader in the same way I use it for jQuery

{test: require.resolve("jquery"), loader: "expose?$!expose?jQuery"},
{test: require.resolve("chessboard"), loader: "expose?ChessBoard!./vendor/chessboard/js/chessboard-0.3.0.min.js"}

But I get "Error: Cannot find module 'chessboard'" error. Same if I replace ChessBoard with $. Not sure what I am doing wrong. Is expose even the right loader for what I am trying to do?

Here is my webpack config for reference (without the broken chessboard expose test)

var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
  entry: ['webpack/hot/dev-server', path.resolve(__dirname, 'app/main.js')],
  output: {
    path: path.resolve(__dirname, 'build'),
    filename: 'bundle.js',
  },
  module: {
    loaders: [
      {test: require.resolve("jquery"), loader: "expose?$!expose?jQuery"},
      {test: /\.jsx?$/, exclude:  /(node_modules|bower_components)/, loader: 'babel', query: {presets: ['react', 'es2015']} }, 
      /* CSS loaders */
      {test: /\.css$/, loader: 'style!css'},
      {test: /\.less$/, loader: 'style!css!less'},
      /* font loaders for bootstrap */
      {test: /\.(woff|woff2)(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=application/font-woff'},
      {test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=application/octet-stream'},
      {test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: 'file'},
      {test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=image/svg+xml'},
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({
      title: 'Test',
      inject: false,
      template: 'node_modules/html-webpack-template/index.ejs',
      appMountId: 'app',
      devServer: 'http://localhost:8080',
    })
  ]
};
like image 321
Mad Wombat Avatar asked Dec 07 '25 06:12

Mad Wombat


1 Answers

The problem seems to be that the chessboard.js is just a anonymous function and not a AMD or CommonJS module, and you may have to look at adding shims using webpack.

Not all JS files can be used directly with webpack. The file might be in an unsupported module format, or not even in any module format. https://github.com/webpack/docs/wiki/shimming-modules

like image 193
Salus Sage Avatar answered Dec 09 '25 18:12

Salus Sage