Angular 6 building a library with assets

dev7 picture dev7 · May 30, 2018 · Viewed 16.9k times · Source

Upon building & packaging an Angular 6 library, I can't seem to be able to instruct the Angular CLI to copy the library's assets into the dist/assets folder on every build.

Assuming the project's folder structure is this -

- dist
- e2e
- node_modules
- projects
  - lib1
    - src
      - lib
      - assets
        - icons
- src

When I run ng build lib1 or ng build lib1 --prod the assets/icons folder is not being copied into dist/lib1/assets/icons.

If I run ng build then src/assets (the root src/assets) is being copied but not projects/lib1/assets.

The angular.json file contains a reference to "assets": ["src/assets"] but it won't allow adding the assets key specifically to the project, only to the main root app. When adding, I get the following error:

Schema validation failed with the following errors: Data path "" should NOT have additional properties(assets).

I also tried adding the following custom copy rule to the assets to copy the assets to dist/lib instead of to dist/appname:

  "assets": [
     "src/favicon.ico",
     "src/assets",
     { "glob": "**/*", "input": "src/assets/icons", "output": "../lib1/assets/icons" }
        ],

But I get the following error:

An asset cannot be written to a location outside of the output path.

Is there a built-in way of managing library asset's copy on every build?

UPDATE 06/05/2018

I opened an issue with Angular CLI regarding this but have not heard back yet. Issue #11701

Answer

dev7 picture dev7 · Jun 5, 2018

Currently, I still have not found an official built-in way to do so.

I opened an Angular CLI issue and hopefully will get the CLI team response.

In the meantime my workaround is using command line tools:

In package.json I added:

"scripts": {
    ...
    "build": "ng build lib1 --prod && scss-bundle -c scss-bundle.config.json && cp -R projects/lib1/src/assets/ dist/lib1/assets/",
}

To copy the SASS files I use scss-bundle with config file scss-bundle.config.json that contains:

{
  "entry": "./projects/lib1/src/assets/style/main.scss",
  "dest": "./dist/lib1/assets/style/styles.scss"
}

This will build the SASS files of the project into 1 file and copy it into the dist folder. My SASS file structure is something like:

-- projects/lib1/src/assets/
                  -- style
                     -- main.scss
                     -- partials
                        -- _variables.scss
                        -- _styles.scss
                        __ _rtl.scss

So as you can see I don't want to ship all the raw sass, just one final file. Of course, you can also compile it into a .css file instead.

To make sure all other assets are copied, I use a simple Mac OS/Linux command cp -R or rsync.

And, of course, instead of running ng build I run npm run build.

Hope this helps, and if you have a better solution please let me know.