Var bar = require(‘bar’) var bar = require(‘bar’)

We use the CommonJS modular specification directory structure

    --demo
        --node_module  // You can create folders manually
            --bar.js
        --demo.js
Copy the code

bar.js

    var str = {
        str: 'I'm under node_module bar.js'
    }
    exports.str = str // Must be exported using modular standards
Copy the code

demo.js

    var str = require('bar')  // The suffix can be omitted
    console.log(str)    // {STR: {STR: 'I am under node_module bar.js'}}
Copy the code

The result of the data is {STR: {STR: ‘I am under node_module bar.js’}}

So when we use it, we need STR. STR is very unfriendly.

Let’s do it the other way

bar.js

    var str = {
        str: 'I'm under node_module bar.js'
    }
    module.exports = str // Must be exported using modular standards
Copy the code

You can see some of the details of the introduction of modular exports

We can already implement it preliminarily if we change the directory structure

    --demo
        --node_module  // You can create folders manually
            --bar
                --bar.js
        --demo.js
Copy the code

Do something about demo.js when you introduce it

    var str = require('bar/bar')  // The suffix can be omitted
    console.log(str)    // {STR: {STR: 'I am under node_module bar.js'}}
Copy the code

That’s not what we’re looking for, either. The big step is coming

We will create a package.json file under the bar folder under node_module

NPM init -y creates the package.json file without prompting

{
  "name": "bar"."version": "1.0.0"."description": ""."main": "bar.js"."scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": []."author": ""."license": "ISC"
}
Copy the code

Note that the main entry already specifies a folder

So we can do that when we use it

    var str = require('bar')  // The suffix can be omitted
    console.log(str)    // {STR: {STR: 'I am under node_module bar.js'}}
Copy the code