Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Property 'ensure' does not exist on type 'NodeRequire'

I'm trying webpack 2 code splitting.

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

the following code should include some.css into a new chunk named '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

like image 784
MrFrag Avatar asked Jan 21 '17 01:01

MrFrag


1 Answers

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

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:

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

1I got the types of ensure from the Webpack docs

like image 140
ahstro Avatar answered Nov 17 '22 00:11

ahstro