Search code examples
npmboweryarnpkgyarn-workspaces

Add packages to custom @frontend_components or lib folder using yarns


When migrated from bower to yarn and ran the command

yarn install

yarn created @bower_components folder and all the bower/front-end components were add inside this folder ../node_modules/@bower_components

"dependencies": {
...
"@bower_components/bootstrap": "twbs/bootstrap#^3.3.7",
"@bower_components/jquery": "jquery/jquery-dist#^3.1.1",
"@bower_components/lodash": "lodash/lodash#^4.17.12",
"@bower_components/moment": "moment/moment#^2.19.1",
... }

If, I need to create migrate from @bower_components to @frontend_components or add to public/lib folder. How do I do it?

yarn --cwd /public/lib add lodash


Solution

  • The workaround which I implemented to resolve this issue was by introducing a simple script and updating the package.json with a new key.

    Under package.json (for all the UI related dependencies needed to work with the front-end)

    ...
    ...
    "scripts": {
        "postinstall": "node migrateUI.js"
      },
    ...
    "uidependencies": {
    ...
    "bootstrap": "^3.3.7"
    "jquery": "^3.1.1",
    "lodash": "*",
    "moment": "^2.19.1",
    ...
    },
    "dependencies": {
    ....
    "bootstrap": "^3.3.7"
    "jquery": "^3.1.1",
    "lodash": "*",
    "moment": "^2.19.1",
    ....
    }
    

    migrateUI.js

    const uipackage = require('./package.json');
    const packageName = Object.keys(uipackage.uidependencies);
    const dir = 'public/libs';
    
     //if the folder already exists, it ignores else creates.
    if (!fs.existsSync(dir)) {
      fs.mkdirSync(dir);
    }
    
    for (let i = 0; i < packageName.length; i++) {
      const element = packageName[i];
      const source = path.resolve('node_modules/' + element);
      const target = path.resolve('public/libs/' + element); //custom lib folder to save all UI dependencies
      if (!fs.existsSync(target)) {
        fs.symlinkSync(source, target, 'dir', (err) => {
          if (err && err.code !== 'EEXIST') {
            console.log('Error creating dependecny symlink - ', err);
          } else {
            console.log('Symlink for dependency created');
          }
        });
      }
    }