Angular 4: "Cannot find name 'require'

Try these steps to fix the error

  1. npm install --save-dev @types/webpack-env

  2. Update your tsconfig.json with the following under compilerOptions:

    "types": [
        "webpack-env"
    ]
    

3.Now go to tsconfig.app.json and add this

"compilerOptions": {
 
    "types": [
      "node"
    ]
   }

require() is not advisable for a few reasons. One, it will "break" the effectiveness of tree-shaking in webpack 2 and two, it will prevent proper code splitting.

A far better alternative is to use webpack's implementation of System.import:

System.import('/assets/js/regular-expresions.js').then(file => {
   // perform additional interactions after the resource has been asynchronously fetched
});

In order to satisfy the Typescript compiler (as you have found), you will need to tell it that System is an acceptable variable by declaring it:

declare var System: any;    

You can either add this line to your component if you only intend to reference it once, or you can add it to the typings.d.ts type definition file to enable its use throughout your app. Note that if you change the typings file, you will need to restart the ng serve session.

This satisfies the compiler at build time and it gets hijacked at runtime by the build system, patching the call through into Webpack's System.import.

Webpack in turn will check to see if it has a chunk that satisfy the requested file and, if it does not, it will dynamically create a script tag and insert it into the head, loading the file with the async attribute, which is what occurs in this case.

Once the file loads, it will be parsed and executed. However, if you want to interact with any part of it via the async .then() callback, your file will need to export anything you wish to invoke, such as:

export function test() {
    console.log('we called test');
}

This will expose the .test() function to your callback handler:

System.import('/assets/js/regular-expresions.js').then(file => {
   file.test();
});

Try adding declare var require: any; on top.