MCPcopy Create free account
hub / github.com/ilearnio/module-alias / init

Function init

index.js:151–213  ·  view source on GitHub ↗

* Import aliases from package.json * @param {object} options

(options)

Source from the content-addressed store, hash-verified

149 * @param {object} options
150 */
151function init (options) {
152 if (typeof options === 'string') {
153 options = { base: options }
154 }
155
156 options = options || {}
157
158 var candidatePackagePaths
159 if (options.base) {
160 candidatePackagePaths = [nodePath.resolve(options.base.replace(/\/package\.json$/, ''))]
161 } else {
162 // There is probably 99% chance that the project root directory in located
163 // above the node_modules directory,
164 // Or that package.json is in the node process' current working directory (when
165 // running a package manager script, e.g. `yarn start` / `npm run start`)
166 candidatePackagePaths = [nodePath.join(__dirname, '../..'), process.cwd()]
167 }
168
169 var npmPackage
170 var base
171 for (var i in candidatePackagePaths) {
172 try {
173 base = candidatePackagePaths[i]
174
175 npmPackage = require(nodePath.join(base, 'package.json'))
176 break
177 } catch (e) {
178 // noop
179 }
180 }
181
182 if (typeof npmPackage !== 'object') {
183 var pathString = candidatePackagePaths.join(',\n')
184 throw new Error('Unable to find package.json in any of:\n[' + pathString + ']')
185 }
186
187 //
188 // Import aliases
189 //
190
191 var aliases = npmPackage._moduleAliases || {}
192
193 for (var alias in aliases) {
194 if (aliases[alias][0] !== '/') {
195 aliases[alias] = nodePath.join(base, aliases[alias])
196 }
197 }
198
199 addAliases(aliases)
200
201 //
202 // Register custom module directories (like node_modules)
203 //
204
205 if (npmPackage._moduleDirectories instanceof Array) {
206 npmPackage._moduleDirectories.forEach(function (dir) {
207 if (dir === 'node_modules') return
208

Callers

nothing calls this directly

Calls 2

addAliasesFunction · 0.85
addPathFunction · 0.85

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…