dimanche 6 juin 2021

Require is not defined even with webpack

I'm working with webpack 5 in a web app that uses node modules. When I run my index.html with a local server I get this error Uncaught ReferenceError: require is not defined.

I have this folder structure:

my_project/
├── node_modules
├── dist/
│    └── main.js
├── src 
│    ├── index.js
│    └── index.html
├── package-lock.json
├── package.json
└── webpack.config.js

My webpack.config.js is:

 // 'webpack-node-externals' is needed because I'm getting the error cannot resolve "http"

const nodeExternals = require('webpack-node-externals')


module.exports = {

  target: 'web',
  externals: [nodeExternals()],

  resolve: {
    fallback: {
      util: require.resolve("util/")
    },
    modules: ['./dist/', './node_modules']
  }
};

And my index.js is:

const Binance = require('node-binance-api');
const binance = new Binance().options({
  APIKEY: '',
  APISECRET: ''
});

console.log(binance)

After run webpack in the terminal,the main.js is created into the dist folder. Finally, I import main.js into index.html like this :

<script type="text/javascript" src="../dist/main.js"></script>

Aucun commentaire:

Enregistrer un commentaire