module#createRequire JavaScript Examples
The following examples show how to use
module#createRequire.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utils.js From vitedge with MIT License | 7 votes |
// Used for printing server info in preview for Vite <= 2.5.x
export async function getViteInternals() {
try {
/* This is just to reuse Vite styles and some logic */
const require = createRequire(import.meta.url)
const vitePath = require.resolve('vite')
let tmp = await fs.readFile(vitePath, 'utf-8')
const [, chunk] = tmp.match(/require\('(\.\/chunks\/.+)'\)/) || []
tmp = null
let internals = await import(path.resolve(path.dirname(vitePath), chunk))
internals = internals.default || internals
return internals
} catch (error) {
console.warn(
'\nCould not import internal Vite module. This likely means Vite internals have been updated in a new version.\n'
)
throw error
}
}
Example #2
Source File: utils.js From slashtags with MIT License | 6 votes |
require = createRequire(import.meta.url)
Example #3
Source File: node-index.js From cbor-x with MIT License | 6 votes |
function tryRequire(moduleId) {
try {
let require = createRequire(import.meta.url)
return require(moduleId)
} catch (error) {
if (typeof window != 'undefined')
console.warn('For browser usage, directly use cbor-x/decode or cbor-x/encode modules. ' + error.message.split('\n')[0])
}
}
Example #4
Source File: index.js From cli with MIT License | 6 votes |
async function startDaemon (name, readable) {
const require = createRequire(import.meta.url)
const daemonRoot = p.dirname(require.resolve(name))
const binPath = p.join(daemonRoot, 'bin', 'index.js')
console.error(`${readable} daemon started`)
return spawn('node', [binPath], {
detached: true
})
}
Example #5
Source File: package.js From ftx-cli with MIT License | 5 votes |
require = createRequire(import.meta.url)
Example #6
Source File: serverUtil.js From asymptoteWebApplication with GNU Lesser General Public License v3.0 | 5 votes |
require = createRequire(import.meta.url)
Example #7
Source File: serverAnalyzer.js From asymptoteWebApplication with GNU Lesser General Public License v3.0 | 5 votes |
require = createRequire(import.meta.url)
Example #8
Source File: typescript.js From kit with MIT License | 5 votes |
/**
* @param {import('types').ValidatedConfig} config
* @param {string} cwd
* @param {import('./types').File[]} files
*/
export async function emit_dts(config, cwd, files) {
const tmp = `${config.kit.outDir}/package/types`;
rimraf(tmp);
mkdirp(tmp);
const require = createRequire(import.meta.url);
const emit = await try_load_svelte2tsx();
await emit({
libRoot: config.kit.files.lib,
svelteShimsPath: require.resolve('svelte2tsx/svelte-shims.d.ts'),
declarationDir: path.relative(cwd, tmp)
});
const handwritten = new Set();
const excluded = new Set();
// remove excluded files, and files that conflict with hand-written .d.ts
for (const file of files) {
if (file.name.endsWith('.d.ts')) {
handwritten.add(file.name);
}
if (!file.is_included) {
excluded.add(file.base + '.d.ts');
excluded.add(file.base + '.d.mts');
excluded.add(file.base + '.d.cts');
}
}
// resolve $lib alias (TODO others), copy into package dir
for (const file of walk(tmp)) {
const normalized = posixify(file);
if (handwritten.has(normalized)) {
console.warn(`Using $lib/${normalized} instead of generated .d.ts file`);
}
// don't overwrite hand-written .d.ts files
if (excluded.has(normalized)) continue;
const source = fs.readFileSync(path.join(tmp, normalized), 'utf8');
write(
path.join(config.kit.package.dir, normalized),
resolve_lib_alias(normalized, source, config)
);
}
}
Example #9
Source File: index.js From playwright-test with MIT License | 5 votes |
require = createRequire(import.meta.url)
Example #10
Source File: runner-tape.js From playwright-test with MIT License | 5 votes |
require = createRequire(import.meta.url)
Example #11
Source File: runner-mocha.js From playwright-test with MIT License | 5 votes |
require = createRequire(import.meta.url)
Example #12
Source File: files.js From vitedge with MIT License | 5 votes |
export function requireJson(path) {
return createRequire(import.meta.url)(path)
}
Example #13
Source File: commons.js From gidget with Apache License 2.0 | 5 votes |
export default function (metaURL = import.meta.url) {
if (typeof metaURL !== 'string') throw new Error("metaURL must be a string");
const require = createRequire(metaURL);
const __filename = fileURLToPath(metaURL);
const __dirname = dirname(__filename);
return { require, __filename, __dirname };
}
Example #14
Source File: getIdBlocksOfHtml.js From rocket with MIT License | 5 votes |
require = createRequire(import.meta.url)
Example #15
Source File: index.js From certd with MIT License | 5 votes |
require = createRequire(import.meta.url)
Example #16
Source File: exports-service.js From certd with MIT License | 5 votes |
require = createRequire(import.meta.url)
Example #17
Source File: index.js From v8-deopt-viewer with MIT License | 5 votes |
/**
* @param {string} srcFile
* @param {import('.').Options} options
*/
export default async function run(srcFile, options) {
let logFilePath;
if (srcFile) {
console.log("Running and generating log...");
logFilePath = await generateV8Log(srcFile, {
logFilePath: path.join(options.out, "v8.log"),
browserTimeoutMs: options.timeout,
traceMaps: !options["skip-maps"],
});
} else if (options.input) {
logFilePath = path.isAbsolute(options.input)
? options.input
: path.join(process.cwd(), options.input);
} else {
throw new Error(
'Either a file/url to generate a log or the "--input" flag pointing to a v8.log must be provided'
);
}
// Ensure output directory exists
await mkdir(options.out, { recursive: true });
console.log("Parsing log...");
const logContents = await readFile(logFilePath, "utf8");
// New IC format has 10 values instead of 9
const hasNewIcFormat = /\w+IC(,.*){10}/.test(logContents);
const rawDeoptInfo = await parseV8Log(logContents, {
keepInternals: options["keep-internals"],
hasNewIcFormat,
});
console.log("Adding sources...");
// Group DeoptInfo by files and extend the files data with sources
const groupDeoptInfo = groupByFile(rawDeoptInfo);
const deoptInfo = {
...groupDeoptInfo,
files: await addSources(groupDeoptInfo.files),
};
const deoptInfoString = JSON.stringify(deoptInfo, null, 2);
const jsContents = `window.V8Data = ${deoptInfoString};`;
await writeFile(path.join(options.out, "v8-data.js"), jsContents, "utf8");
console.log("Generating webapp...");
const template = await readFile(templatePath, "utf8");
const indexPath = path.join(options.out, "index.html");
await writeFile(indexPath, template, "utf8");
// @ts-ignore
const require = createRequire(import.meta.url);
const webAppIndexPath = require.resolve("v8-deopt-webapp");
const webAppStylesPath = webAppIndexPath.replace(/.js$/g, ".css");
await copyFile(webAppIndexPath, path.join(options.out, "v8-deopt-webapp.js"));
await copyFile(
webAppStylesPath,
path.join(options.out, "v8-deopt-webapp.css")
);
if (options.open) {
await open(pathToFileURL(indexPath).toString(), { url: true });
console.log(
`Done! Opening ${path.join(options.out, "index.html")} in your browser...`
);
} else {
console.log(
`Done! Open ${path.join(options.out, "index.html")} in your browser.`
);
}
}
Example #18
Source File: dependencies.js From cs-wiki with GNU General Public License v3.0 | 5 votes |
require = createRequire(import/*::(_)*/.meta.url)
Example #19
Source File: buildWAF.js From pentestkit with MIT License | 5 votes |
require = createRequire(import.meta.url)
Example #20
Source File: build.js From pentestkit with MIT License | 5 votes |
require = createRequire(import.meta.url)
Example #21
Source File: index.js From Front-end-learning-to-organize-notes with MIT License | 5 votes |
commonJSTSLib = createRequire(import.meta.url)("../../tslib.js")
Example #22
Source File: test.js From HinataMd with GNU General Public License v3.0 | 5 votes |
require = createRequire(__dirname)
Example #23
Source File: owner-exec.js From HinataMd with GNU General Public License v3.0 | 5 votes |
require = createRequire(__dirname)
Example #24
Source File: main.js From HinataMd with GNU General Public License v3.0 | 5 votes |
global.__require = function require(dir = import.meta.url) { return createRequire(dir) }
Example #25
Source File: index.js From HinataMd with GNU General Public License v3.0 | 5 votes |
require = createRequire(__dirname)
Example #26
Source File: index.js From vitedge with MIT License | 4 votes |
export default async function ({
mode = 'production',
ssr,
watch,
entry,
worker,
...workerFlags
} = {}) {
const { config: viteConfig, rootDir } = await getProjectInfo(mode)
const {
getFramework,
pluginOptions: {
fnsOptions = {},
workerOptions = {},
clientOptions = {},
ssrOptions = {},
},
} = viteConfig.plugins.find((plugin) => plugin.name === 'vitedge') || {}
const { getPropsHandlerNames } = await buildFunctions({
mode,
watch,
root: rootDir,
fnsInputPath: path.resolve(rootDir, fnsInDir),
fnsOutputPath: path.resolve(rootDir, outDir),
fileName: fnsOutFile,
options: fnsOptions,
})
const sep = '|'
const plugins = [
{
name: 'vitedge-props-replacer',
transform(code, id) {
// Use `transform` hook for replacing variables because `config`
// hook is not retriggered on watcher events.
if (id.endsWith('/vitedge/utils/props.js')) {
watch && this.addWatchFile(path.resolve(rootDir, outDir, fnsOutFile))
return code.replace(
'globalThis.__AVAILABLE_PROPS_ENDPOINTS__',
JSON.stringify(sep + getPropsHandlerNames().join(sep) + sep)
)
}
},
},
]
await buildSSR({
clientOptions: mergeConfig(
{
mode,
plugins,
build: {
watch,
outDir: path.resolve(rootDir, outDir, clientOutDir),
},
},
clientOptions
),
serverOptions: mergeConfig(
{
mode,
ssr: { target: 'webworker' },
plugins,
build: {
ssr,
outDir: path.resolve(rootDir, outDir, ssrOutDir),
target: 'es2019', // Support Node 12
rollupOptions: {
output: {
format: 'es',
},
},
},
packageJson: {
type: 'module',
vitedge: {
commitHash: getCommitHash(),
},
},
},
ssrOptions
),
})
if (getFramework() === 'react') {
// FIXME This is a workaround related to @vite/plugin-react and type:module
const ssrDistDirectory = path.resolve(rootDir, outDir, ssrOutDir)
const require = createRequire(import.meta.url)
const packageJson = require(path.join(ssrDistDirectory, 'package.json'))
const serverBundlePath = path.join(ssrDistDirectory, packageJson.main)
const serverBundle = await fs.readFile(serverBundlePath, 'utf-8')
await fs.writeFile(
serverBundlePath,
serverBundle
.replace('"react/jsx-runtime"', '"react/jsx-runtime.js"')
.replace('"react-router-dom/server"', '"react-router-dom/server.js"'),
'utf-8'
)
}
if (entry === undefined || entry === true) {
const defaultEntry = lookupFile({
dir: path.resolve(rootDir, fnsInDir),
formats: ['js', 'ts', 'mjs'].map((ext) => 'index.' + ext),
pathOnly: true,
bubble: false,
})
entry = defaultEntry || false
}
if (entry) {
const wranglerConfig = await getWranglerConfig(viteConfig)
const isWorker = !!(worker || wranglerConfig)
if (isWorker && wranglerConfig.type !== 'javascript') {
// Do not build script when using Webpack
return
}
await buildWorker({
...workerFlags,
watch,
esbuildOptions: workerOptions.build,
inputPath: entry,
viteConfig,
platform: isWorker ? 'worker' : 'node',
fileName: isWorker ? workerOutFile : nodeOutFile,
outputPath: isWorker ? path.join(outDir, workerOutDir) : outDir,
})
}
}