Joe*_*iak 5 browser node.js webpack umd
我正在制作一个模块,我希望它可以在浏览器和 Node.js 中使用。它依赖于性能,这给我使用 Webpack 和 Node.js 中的 perf_hooks 模块带来了麻烦。无论我做什么,我只能在其中之一起作用的地方得到它,但不能同时得到两者。
以下是我尝试过的大部分内容。我的问题是,如何配置 Webpack 以在节点中需要 perf_hooks,但在浏览器中使用内置的性能全局?
这是我的基本 Webpack 配置:
const path = require('path');
module.exports = {
entry: './src/UpdateLoop.js',
mode: 'development',
output: {
library: 'UpdateLoop',
libraryTarget: 'umd',
path: path.resolve(__dirname, 'dist'),
filename: 'updateloop.js',
globalObject: 'this',
},
};
Run Code Online (Sandbox Code Playgroud)
给我带来麻烦的代码:
const { performance } = require('perf_hooks');
Run Code Online (Sandbox Code Playgroud)
webpack 中出现此错误:
Field 'browser' doesn't contain a valid alias configuration
resolve as module
C:\Users\joe.jankowiak\projects\update-loop\src\node_modules doesn't exist or is not a directory
Run Code Online (Sandbox Code Playgroud)
我已经看到“fs”执行以下操作的建议:
// configuration.node has an unknown property 'perf_hooks'
node: {
perf_hooks: false,
},
// configuration has an unknown property 'browser'.
browser: {
perf_hooks: false,
},
Run Code Online (Sandbox Code Playgroud)
然后我看到人们推荐使用“解决”:
// Compiles, but complains performance doesn't exist in node or browser.
resolve: {
fallback: {
perf_hooks: false,
}
},
Run Code Online (Sandbox Code Playgroud)
// Works in browser but doesn't work in node. Node complains about using performance before its defined:
performance = performance || require('perf_hooks').performance;
Run Code Online (Sandbox Code Playgroud)
// Doesn't work in either
const performance = performance || require('perf_hooks').performance;
Run Code Online (Sandbox Code Playgroud)
// Trying to check if its node, but with resolve its making perf_hooks null in node
if(typeof __webpack_require__ === 'function') {
global.performance = require('perf_hooks').performance;
}
Run Code Online (Sandbox Code Playgroud)
我最终出于懒惰而这样做,因为我仍然不太明白如何在 Webpack 中使用 NodeJS 函数:
function portableMsecTimer () {
if (process.hrtime) {
return Number(process.hrtime.bigint()) / 1e6;
} else {
return window.performance.now();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
861 次 |
| 最近记录: |