Using Node.js modules in HTML

后端 未结 3 2040
既然无缘
既然无缘 2021-01-12 12:04

I have the following Node.js project (which is a Minimal Working Example of my problem):

module1.js:

module.exports = function() {
          


        
3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-12 12:21

    The problem is that you're using CJS modules, but still try to play old way with inline scripts. That won't work, it's either this or that.

    To take full advantage of CJS style, organize your client-side code exactly same way as you would for server-side, so:

    Create client.js:

    var module2 = require('./module2');
    console.log(module2());  // prints: "this is module1! and this is module2!"
    

    Create bundle with Browserify (or other CJS bundler of your choice):

    browserify client.js > client.bundle.js
    

    Include generated bundle in HTML:

    
    

    After page is loaded you should see "this is module1! and this is module2!" in browser console

提交回复
热议问题