Use node Path module with angular 6

Viewed 8219

I'm trying to use the module Path in an Angular 6 project.

I found this post to fix the issue :

https://gist.github.com/niespodd/1fa82da6f8c901d1c33d2fcbb762947d

it says to add a script :

const fs = require('fs');
const f = 'node_modules/@angular-devkit/build-angular/src/angular-cli-files/models/webpack-configs/browser.js';

fs.readFile(f, 'utf8', function (err,data) {
  if (err) {
    return console.log(err);
  }
  var result = data.replace(/node: false/g, 'node: {crypto: true, stream: true}');

  fs.writeFile(f, result, 'utf8', function (err) {
    if (err) return console.log(err);
  });
});

And declare it in package.json :

{...
  "scripts": {
    "postinstall": "node patch.js",
    ...
  }
}

But when I'm trying to use it in a service, just import it like this :

import {join} from 'path';

It says that the module Path cannot be found.


How can I correct this ?

2 Answers

Interesting problem.

I managed to get Path module work on my Angular project.

Here are the steps.I use node 8, angular 6.

1: install path.

  npm install path 

This is an exact copy of the NodeJS ’path’ module published to the NPM registry.

2, I also installed @types/node as in Angular we are using typescript. Although later I removed this module and path module seems still works.

3, run the above script using

node patch.js

I manually run it and go to 'node_modules/@angular-devkit/build-angular/src/angular-cli-files/models/webpack-configs/browser.js' to check the file actually changed.

4, I put

  import {join} from 'path';

in one of my component.ts file

 let x = join('Users', 'Refsnes', '..', 'demo_path.js');
    console.log("-------------------------------------------------");
    console.log(x);

in a Component's onInit() function.

and run "ng serve" I saw the expected output in my console when loading the webpage.

-------------------------------------------------
Users/demo_path.js

So this method does work. I am not sure which step you did wrong. My guess would be the first step as I tried if not do step 3 there's different error message. Please check your node_modules folder and verify path folder exists and reinstall it if necessary.

  1. Be sure to have node types installed: npm install --save-dev @types/node
  2. Import path: import * as path from 'path';
Related