mercredi 29 juillet 2020

How to correctly utilize webpack for both node.js and browser applications

So I have been developing a web application that does some data processing. However with the limited supports for loading file from local, testing my code was brutal on browser.

Therefore, I wanted to set my project up in a way that I can write single js file for core functions and compile it for both browser and node.js so that I can test things using node.js and power up my web applications using the same code.

I found that webpack would be a good solution but how to correctly setup what I want was unclear. All the tutorial had pieces of what I wanted that when I put things together it falls apart.

In the ideal scenario, I would like to have the following set of files to run without error with correct output

  • ./src/common/utils.js
var square = function(x) {
    return x * x;
}

module.exports = square;
  • ./src/index.js
import {square} from "./common/utils";
  • ./src/index.html
<tags ... >
  <script type="text/javascript">
    console.log(square(3))
  </script>
<tags ... >
  • ./app.js
const square = require('./src/common/utils.js');
console.log(square(3))

I have separate webpack config

  • webpack-front.config.js : compile things to ./browser_dist/* with HtmlWebPackPlugin of template ./src/index.html
  • webpack-back.config.js : compile things to ./node_dist/* with entry of app.js

I have noticed that node.js version works as expected when I run following commands

webpack --config webpack-back.config.js
node node_dist/app.js

However, ween I run webpack --config webpack-front.config.js and open index.html on browser, I was seeing Uncaught ReferenceError: square is not defined

I know that webpack compiles everything into single main.js file and load it automatically for index.html. However, eventually I have multiple html pages and would like to have each one load different js (controller files) that exposes a set of functions upon include () as in the case of typical web application.

Can anyone guide me on how to set this up right? If I need to provide more information, I will do so.




Aucun commentaire:

Enregistrer un commentaire