How to add multiple NODE_PATH in package.json?

2020-08-20 08:37发布

问题:

How do I add multiple NODE_PATH in package.json?

I want to have these multiple paths:

NODE_PATH=./ NODE_PATH=./modules/

or

NODE_PATH=./lib NODE_PATH=./modules/

package.json:

{
  "name": "my-app",
  "description": "env",
  "repository": "https://github.com/xxx.git",
  "scripts": {
    "dev": "NODE_PATH=./lib NODE_PATH=./ node server.js",
    "start": "cross-env NODE_ENV=production NODE_PATH=./ NODE_PATH=./modules/ nodemon --exec babel-node --presets es2015 server.js"
  },
  "dependencies": {
    "cross-env": "^5.0.5",
    "express": "^4.15.4"
  },
  "license": "MIT"
}

server.js:

'use strict'

import express from 'express'
import sample from 'lib/sample'
import config from 'lib'

const app = express()
const isProd = (process.env.NODE_ENV === 'production')
const port = process.env.PORT || 3000
console.log(isProd)
console.log(sample)
console.log(config)

app.get('/', function (req, res) {
  const data = {message: 'Hello World!'}
  console.log(data);
  return res.status(200).json(data);
})

app.listen(port, function () {
  console.log('listening on port 3000!')
})

Error:

Error: Cannot find module 'lib/sample'

Any ideas?

回答1:

The way you are using NODE_PATH in your example, by setting it twice, you are overwriting the writing the value you assign first with the second time.

Instead, set NODE_PATH to multiple paths, delimited by colons (on MacOS or Linux) or semicolons (Windows), like this:

{
    "name": "my-app",
    "description": "env",
    "repository": "https://github.com/xxx.git",
    "scripts": {
        "dev": "NODE_PATH=./lib:./ node server.js",
        "start": "cross-env NODE_ENV=production NODE_PATH=./:./modules/ nodemon --exec babel-node --presets es2015 server.js"
    },
    "dependencies": {
        "cross-env": "^5.0.5",
       "express": "^4.15.4"
    },
    "license": "MIT"
}

See Node.js documentation:

https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders