从外部 webpack 导入(运行时导入) [英] Importing from outside webpack (runtime importing)

查看:34
本文介绍了从外部 webpack 导入(运行时导入)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<块引用>

这只是我今天想到的事情,我没有看到很多信息,所以我将分享这个奇怪案例以及我个人如何解决这些问题(如果有更好的方法请评论,但同时这可能会帮助其他人^^)

在 webpack bundle 中,你所做的每一个 import/require 都由 webpack 使用其内部的 require 函数管理.这意味着如果你在 webpack 包中,你就不能再使用原始的 NodeJS 全局 require.

<块引用>

另见:从外部 webpack 包导出

解决方案

其实 webpack 提供了一个解决方法:

一个名为 __non_webpack_require__ 的变量,它是原始的 require 所以,在你的代码中,你可以这样做:

const internalModule = require('internal/module');//或从内部/模块"导入内部模块;以 ES6 方式const externalModule = __non_webpack_require__('external/module');

如果您使用的是 TypeScript,您可以在 global.d.ts 文件中添加这一行以避免语法错误:

声明 const __non_webpack_require__: NodeRequireFunction;

<块引用>

事实1:其实在构建之后,你可以看到你常用的require(webpack的)是如何被重命名为__webpack_require__的,并且__non_webpack_require__ 已作为原始 require 保留.

事实 2: Webpack 也使用原来的 require 从系统导入模块(不与代码捆绑),例如 neteventsfs

This is just something I thought today and I didn't see a lot of information so I'm going to share this weird cases and how I personally solved them (if there's a better way please comment, but meanwhile this might help others ^^)

In a webpack bundle, every import/require you do, is managed by webpack using their internal require function. That means you cannot use anymore the original NodeJS global require if you are inside a webpack bundle.

See also: Exporting from outside webpack bundle

解决方案

There's a workaround provided by webpack actually:

A variable called __non_webpack_require__ which is the original require so, in your code, you can do this:

const internalModule = require('internal/module');
// or import internalModule from 'internal/module'; in the ES6 way

const externalModule = __non_webpack_require__('external/module');

If you are using TypeScript, you can add this line in your global.d.ts file to avoid syntax errors:

declare const __non_webpack_require__: NodeRequireFunction;

Fact 1: Actually after the build, you can see how your commonly used require (webpack's) has been renamed to __webpack_require__, and that __non_webpack_require__ has been preserved as the original require.

Fact 2: Webpack also use the original require to import modules from the system (not bundled with the code), such as net, events, fs, etc.

这篇关于从外部 webpack 导入(运行时导入)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆