类型'NodeRequire'上不存在属性'ensure'

时间:2022-10-01 23:00:02

I'm trying webpack 2 code splitting.

我正在尝试webpack 2代码拆分。

According to this doc: https://webpack.js.org/guides/code-splitting-require/

根据这个文档:https://webpack.js.org/guides/code-splitting-require/

the following code should include some.css into a new chunk named 'something'

以下代码应该将some.css包含在一个名为'something'的新块中

require.ensure([], function(require) {
    require('some.css');
}, 'something');

but when I run it, I get this error:

但是当我运行它时,我收到此错误:

ERROR in ./src/index.ts
(4,9): error TS2339: Property 'ensure' does not exist on type 'NodeRequire'.

Any idea about how to fix it? Thanks

有关如何解决它的任何想法?谢谢

2 个解决方案

#1


4  

The way I solved this was by creating my own interface - WebpackRequire - which extends NodeRequire with ensure1.

我解决这个问题的方法是创建我自己的接口--WebpackRequire - 它使用ensure1扩展NodeRequire。

interface WebpackRequire extends NodeRequire {
  ensure(
    dependencies: string[],
    callback: (require: WebpackRequire) => void,
    errorCallback?: (error: Error) => void,
    chunkName?: string
  ): void;
};

If you've only got a single instance of require.ensure, you can then type cast it to a WebpackRequire using (require as WebpackRequire).ensure, but since I used it multiple times in a module, I created local require at the top scope of the module, type cast as WebpackRequire, like this:

如果您只有一个require.ensure实例,那么您可以使用(require as WebpackRequire).ensure将其转换为WebpackRequire,但由于我在模块中多次使用它,我在顶部创建了本地需求模块的范围,类型转换为WebpackRequire,如下所示:

const require: WebpackRequire = (window as any).require;

1I got the types of ensure from the Webpack docs

1我从Webpack文档中获得了类型的保证

#2


0  

I required a javascript document which then did the require. Not exactly the nicest solution, but it did work

我需要一个javascript文档然后执行要求。这不是最好的解决方案,但确实有效

#1


4  

The way I solved this was by creating my own interface - WebpackRequire - which extends NodeRequire with ensure1.

我解决这个问题的方法是创建我自己的接口--WebpackRequire - 它使用ensure1扩展NodeRequire。

interface WebpackRequire extends NodeRequire {
  ensure(
    dependencies: string[],
    callback: (require: WebpackRequire) => void,
    errorCallback?: (error: Error) => void,
    chunkName?: string
  ): void;
};

If you've only got a single instance of require.ensure, you can then type cast it to a WebpackRequire using (require as WebpackRequire).ensure, but since I used it multiple times in a module, I created local require at the top scope of the module, type cast as WebpackRequire, like this:

如果您只有一个require.ensure实例,那么您可以使用(require as WebpackRequire).ensure将其转换为WebpackRequire,但由于我在模块中多次使用它,我在顶部创建了本地需求模块的范围,类型转换为WebpackRequire,如下所示:

const require: WebpackRequire = (window as any).require;

1I got the types of ensure from the Webpack docs

1我从Webpack文档中获得了类型的保证

#2


0  

I required a javascript document which then did the require. Not exactly the nicest solution, but it did work

我需要一个javascript文档然后执行要求。这不是最好的解决方案,但确实有效