How to combine several files in one js file in which there is a function:

require('./main') require('./result') require('./solution') 

After installing the npm package on the local server, files are correctly processed by the browser. And when I cling main.js file in which there are require() to html. Then he writes errors on another server

Uncaught Error: Mismatched anonymous define () module:

Are there any tools to get one js file where all the dependencies are already in place?

You need to attach the js code to a file on the server where you cannot put a node or something like that. That is, js should be processed purely on the client and that's it. It should not load anything.

    1 answer 1

    There are such tools, and there are many of them.

    This class of tools is called an “assembly system”. The essence of their work is reduced to building an AST tree using JS code to search for all dependencies and substitute the require functions for the collector-specific code. At the output, you get one JavaScript file, with all your code (and dependencies) inside.

    As an example, I will give an example of using two popular build systems: Browserify and Webpack . (There are others, but Google will tell you better about them than me.)

    Browserify appeared earlier than Webapack and solves a somewhat narrower range of tasks (see the description of the Webpack below). For global installation, just run the command:

     npm install -g browserify 

    To build the project you need to run:

     browserify main.js -o bundle.js 

    where main.js is the entry point of your application, and bundle.js is the name of the resulting file.

    Webpack , unlike Browserify, was created not only to collect JavaScript code. This build environment extends the usability of the require function by allowing you to use it to connect:

    • pictures
    • CSS files
    • files written for CSS preprocessors (LESS / SASS / ...)
    • source code in languages ​​compiled in JS (CoffeeScript, etc.)
    • of patterns

    Each type of dependency is handled differently depending on the Webpack configuration. At the output, you get a set of files ready to be directly connected to the HTML page.

    If we talk only about JS applications, then Webpack can work similarly to Browserify. For global installation, you just need to run the command:

     npm install webpack -g 

    To build the project you need to run:

     webpack ./entry.js bundle.js 

    where ./entry.js is the entry point of your application, and bundle.js is the name of the resulting file.

    Comment

    Additionally, you can read about common modular systems in JS in my other answer .