Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: use createRequire to load/resolve modules #5092

Merged
merged 2 commits into from Jan 23, 2020
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
34 changes: 27 additions & 7 deletions packages/@vue/cli-shared-utils/lib/module.js
@@ -1,18 +1,34 @@
const Module = require('module')
const path = require('path')

const semver = require('semver')

// https://github.com/benmosher/eslint-plugin-import/pull/1591
// https://github.com/benmosher/eslint-plugin-import/pull/1602
// Polyfill Node's `Module.createRequireFromPath` if not present (added in Node v10.12.0)
// Use `Module.createRequire` if available (added in Node v12.2.0)
const createRequire = Module.createRequire || Module.createRequireFromPath || function (filename) {
const mod = new Module(filename, null)
mod.filename = filename
mod.paths = Module._nodeModulePaths(path.dirname(filename))

mod._compile(`module.exports = require;`, filename)

return mod.exports
}

function resolveFallback (request, options) {
const Module = require('module')
const isMain = false
const fakeParent = new Module('', null)

const paths = []

for (let i = 0; i < options.paths.length; i++) {
const path = options.paths[i]
fakeParent.paths = Module._nodeModulePaths(path)
const p = options.paths[i]
fakeParent.paths = Module._nodeModulePaths(p)
const lookupPaths = Module._resolveLookupPaths(request, fakeParent, true)

if (!paths.includes(path)) paths.push(path)
if (!paths.includes(p)) paths.push(p)

for (let j = 0; j < lookupPaths.length; j++) {
if (!paths.includes(lookupPaths[j])) paths.push(lookupPaths[j])
Expand All @@ -35,9 +51,13 @@ const resolve = semver.satisfies(process.version, '>=10.0.0')
exports.resolveModule = function (request, context) {
let resolvedPath
try {
resolvedPath = resolve(request, {
paths: [context]
})
try {
resolvedPath = createRequire(context).resolve(request)
sodatea marked this conversation as resolved.
Show resolved Hide resolved
} catch (e) {
resolvedPath = resolve(request, {
paths: [context]
})
}
} catch (e) {}
return resolvedPath
}
Expand Down