如何在package.json中添加多个NODE_PATH?
我希望拥有以下多条路径:
NODE_PATH=./ NODE_PATH=./modules/
或
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!')
})
错误:
错误:找不到模块'lib / sample'
有什么想法吗?
答案 0 :(得分:8)
您在示例中使用 NODE_PATH 的方式,通过设置两次,您将覆盖第二次首先分配的值。
相反,将 NODE_PATH 设置为多个路径,由冒号(在MacOS或Linux上)或分号(Windows)分隔,如下所示:
{
"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"
}
请参阅Node.js文档:
https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders