Angular (+ CLI) 6.0.0: Global styles for libraries
Versions
Angular CLI: 6.0.1
Node: 8.9.4
OS: win32 x64
Angular:
...
Package Version
------------------------------------------------------
@angular-devkit/architect 0.6.1
@angular-devkit/core 0.6.1
@angular-devkit/schematics 0.6.1
@schematics/angular 0.6.1
@schematics/update 0.6.1
rxjs 6.1.0
typescript 2.7.2
Repro steps
- Step 1: generate a new library
- Step 2: add some global styles to the library
- Step 3: run
ng build your-library - Step 4: global styles are not in
./dist
Observed behavior
The global styles from the library are not copied/used
Desired behavior
Global styles inside a library should be part of the generated output. I know that I could use component level styles (this works). However this doesnt work in all use cases. For example I have some css to style buttons but I dont have a ButtonComponent (and I dont want one) since I am only modifying the html <button> tag with the css and I am not adding some behaviour.
Mention any other details that might be useful (optional)
I tried to add styles: [] in my angular.json but get a
Schema validation failed with the following errors:
Data path "" should NOT have additional properties(styles).
https://github.com/angular/angular-cli/wiki/stories-global-styles shows, how to use global styles. This does not work when you add them into your library json configuration
"my-library": {
[...]
"architect": {
"build": {
"builder": "@angular-devkit/build-ng-packagr:build",
"options": {
[...]
"styles": [
"styles/styles.scss"
]
[...]
The documentation feels misleading since this does work for app builds but not for libraries. Or am I doing something wrong?
The options are particular to the referenced builder (in this case, "builder": "@angular-devkit/build-ng-packagr:build",). Both it and ng-packagr would need to add support to allow for such an option.
Okay - I've used ng-packgr before. Afaik there's no support for global css in ng-packagr and I had to add own build steps in order to get this running
Since having a global css file seems to me like a common thing, is there any plan to collab with the ng-packagr project on this?
Any update on this?
@jhuenges if it helps, here's a gulp task snippet as workaround (or long-term solution, depending on what the angular team is planning 😃 )
The snippet includes:
- Building with
ng build my-lib --prod - Merging different (s)css files into one and concat them
- Copy additional assets, e.g. font-files
const gulp = require('gulp');
const sass = require('gulp-sass');
const concat = require('gulp-concat');
const run = require('gulp-run');
const projectName = 'your-library';
const distDir = './dist/' + projectName;
gulp.task('build:angular-package', function () {
return run('ng build ' + projectName + ' --prod', {}).exec();
});
gulp.task('build:sass', ['build:angular-package'], function () {
return gulp.src(['./src/lib/styles/styles.scss', './src/assets/**/*.scss'])
.pipe(sass().on('error', sass.logError))
.pipe(concat('styles.css'))
.pipe(gulp.dest(distDir));
});
gulp.task('build:copy-assets', ['build:angular-package'], function () {
return gulp.src(['src/assets/fonts/icons8/*', 'src/assets/fonts/opensans/v15/*'])
.pipe(gulp.dest(distDir));
});
gulp.task('build', [
'build:angular-package',
'build:sass',
'build:copy-assets'
]);
I had to change a couple of things since we have a slightly different custom-build but it should give an idea on how you can solve this.
Of course you need to install the necessary gulp-packages.
Thanks! I will try to use this, but an official solution would be great :)
Here is another solution using only node package. In your package.json add dependency to package cpx and scss-bundle.
Then add the following entries in your package.json "scripts" property :
"scripts": {
...
"build-mylib": "ng build mylib && npm run build-mylib-styles && npm run cp-mylib-assets",
"build-mylib-styles": "cpx \"./projects/mylib/src/lib/style/**/*\" \"./dist/mylib/style\" && scss-bundle -e ./projects/mylib/src/lib/style/_style.scss -d ./dist/mylib/style/_styles.scss",
"cp-mylib-assets": "cpx \"./src/assets/**/*\" \"./dist/mylib/assets\"",
}
The build-mylib-styles works in two steps. First it copys all styles files found in the lib/style folder and then it uses the scss-bundle package to bundle all imports of the _style.scss file. I have other files in the lib/style folder without import so no need to bundle them.
Hi. I wrote another solution that adapts to the projects/** directory structure for multiple library projects:
./projects
my-lib/
src/
lib/
my-lib-component/
my-lib.component.css
./src
assets/
sass/
projects/
my-lib/
my-lib-component/
my-lib.component.scss
gulpfile.js:
let gulp = require('gulp');
let sass = require('gulp-sass');
let autoprefixer = require('gulp-autoprefixer');
const aliases = require('gulp-style-aliases');
let fs = require('fs');
let path = require('path');
let cssTaskDictionary = [];
let cssTaskList = [];
let watchTaskList = [];
// SRC PATH definitions
let publicFolder = './projects';
let srcFolder = './src/assets';
let cssSrcPath = `${srcFolder}/sass/projects`;
let cssDest = `${publicFolder}`;
// Gather Scss src files to watch and compile
(fs.readdirSync(cssSrcPath) || []).filter(directory => {
let isDirectory = fs.lstatSync(path.join(cssSrcPath, directory)).isDirectory();
return !/global/.test(directory) &&
!/theme/.test(directory) &&
isDirectory;
}).forEach(project => {
(fs.readdirSync(path.join(cssSrcPath, project)) || []).filter(projectCtrl => {
return fs.lstatSync(path.join(cssSrcPath, project, projectCtrl)).isDirectory();
}).forEach(directory => {
fs.readdirSync(path.join(cssSrcPath, project, directory)).forEach(file => {
cssTaskDictionary.push({ project: project, directory: directory, file: file });
});
});
});
cssTaskDictionary.forEach(taskDef => {
let file = taskDef.file.replace(/\.scss/, '');
file = file.replace(/_/, '');
let taskSuffix = '-' + taskDef.project + '-' + taskDef.directory + '-' + file;
let taskName = 'css' + taskSuffix;
cssTaskList.push(taskName);
// Sass will watch for changes in this file
let srcPathFile = path.join(cssSrcPath, taskDef.project, taskDef.directory, taskDef.file);
let destination = path.join(cssDest, taskDef.project, '/src/lib', taskDef.directory);
gulp.task(taskName, () => {
gulp.src([srcPathFile])
.pipe(aliases({
'@bootstrap': 'node_modules/bootstrap/scss',
'@ebm': 'node_modules/ebm',
'@sass': 'src/assets/sass',
}))
.pipe(sass({
outputStyle: 'compressed'
}).on('error', sass.logError))
.pipe(autoprefixer({
browsers: ['last 2 versions'],
cascade: false,
flexbox: true,
}))
.pipe(gulp.dest(destination)
);
});
// Instantiate directory specific watch tasks
let watchTaskName = 'watch-' + taskName;
watchTaskList.push(watchTaskName);
gulp.task(watchTaskName, () => {
gulp.watch([srcPathFile], [taskName]);
});
});
gulp.task('watch', watchTaskList);
This might be a good read when a official solution is not yet ready: https://medium.com/@Dor3nz/compiling-css-in-new-angular-6-libraries-26f80274d8e5
Here is another solution using only node package. In your package.json add dependency to package
cpxandscss-bundle. Then add the following entries in your package.json "scripts" property :"scripts": { ... "build-mylib": "ng build mylib && npm run build-mylib-styles && npm run build-mylib-assets", "build-mylib-styles": "cpx \"./projects/mylib/src/lib/style/**/*\" \"./dist/mylib/style\" && scss-bundle -e ./projects/mylib/src/lib/style/_style.scss -d ./dist/mylib/style/_styles.scss", "build-mylib-assets": "cpx \"./src/assets/**/*\" \"./dist/mylib/assets\"", }The build-mylib-styles works in two steps. First it copys all styles files found in the lib/style folder and then it uses the scss-bundle package to bundle all imports of the _style.scss file. I have other files in the lib/style folder without import so no need to bundle them.
Thanks! this solution works well. However, the new watch mode for the library doesn't work after this. So, one needs to rebuild and serve the page manually after any code change. Any way to make the watch mode work with this?
but while packaging angular try to remove the script section of package.json and the following message occurs:
Removing scripts section in package.json as it's considered a potential security vulnerability.
Why would you do that?!
@ramandeep-singh-1983 i got it to work with watch mode, for everything except the scss-bundle, which i guess has to be a post-build step.
i used concurrently and rimraf, in addition to the already mentioned cpx and scss-bundle
here's the scripts i developed for it:
"scripts": {
"clean": "rimraf \"./dist/*\"",
"scss-bundle": "scss-bundle -e \"./framework/src/styles/_framework.scss\" -d \"./dist/framework/styles/_framework.scss\"",
"watch-ts": "ng build --watch=true",
"watch-scss": "cpx \"./framework/src/styles/**/*\" \"./dist/framework/styles\" --watch --verbose",
"watch-assets": "cpx \"./framework/src/assets/**/*\" \"./dist/framework/assets\" --watch --verbose",
"watchAll": "npm run clean & concurrently \"npm:watch-*\""
},
i put in the clean step because i have configured my ng-package.json with "deleteDestPath": false
this allows me to control the deleting of the output folder myself.
that way ng build --watch doesn't keep wiping out the work done by cpx every time a .ts file changes
i opened an issue in scss-bundle repo to ask them about adding a -watch mode https://github.com/SimplrJS/scss-bundle/issues/57
Would love to know when there is a general solution. For now I am just creating a core-component which loads in the styles which I have to reference once above my app-root. Not as nice, but works for now. You might have to add the core-component to the bootstrap next to you app-root for it to work. Otherwise load it once in your app-component.
[...]
i opened an issue in scss-bundle repo to ask them about adding a -watch mode SimplrJS/scss-bundle#57
Thanks to @hughanderson4 there is now a watch mode for scss-bundle (see version 2.5.0-beta)
@ramandeep-singh-1983 i got it to work with watch mode, for everything except the scss-bundle, which i guess has to be a post-build step.
i used concurrently and rimraf, in addition to the already mentioned cpx and scss-bundle
here's the scripts i developed for it:
"scripts": { "clean": "rimraf \"./dist/*\"", "scss-bundle": "scss-bundle -e \"./framework/src/styles/_framework.scss\" -d \"./dist/framework/styles/_framework.scss\"", "watch-ts": "ng build --watch=true", "watch-scss": "cpx \"./framework/src/styles/**/*\" \"./dist/framework/styles\" --watch --verbose", "watch-assets": "cpx \"./framework/src/assets/**/*\" \"./dist/framework/assets\" --watch --verbose", "watchAll": "npm run clean & concurrently \"npm:watch-*\"" },i put in the clean step because i have configured my ng-package.json with
"deleteDestPath": falsethis allows me to control the deleting of the output folder myself. that wayng build --watchdoesn't keep wiping out the work done bycpxevery time a .ts file changesi opened an issue in scss-bundle repo to ask them about adding a -watch mode SimplrJS/scss-bundle#57
@hughanderson4 your solution is great, but I encountered a problem while using it. The ng build --watch command automatically clean the dist folder. When running the assets/css/bundle scripts in parallel with the ng build, the cpx and scss-bundle commands are executed before the ng build dist cleaning resulting in the deletation of the newly copied files.
To overcome this situation :
- Use Angular-cli 7.1 which has a new option (--deleteOutputPath=false) and use the rimraf command to enrue dist cleaning is proceeded before any other script is executed.
- If using previous Angular version : add a short delay before using cpx, scss-bundle (using npm package like @sindresorhus delay-cli)
Yeah buddy similarly in my lib I got a ng-package.json and I had to modify like this to prevent the cleaning of the output folder:
{
...
"deleteDestPath": false,
...
}
That why I manually put in the rimraf step. Since ng build not doing that for me anymore.
I had problems trying to run all of it concurrently. My workflow is to start the watch-ts and then after it has done the initial build then I start the watch-assets and watch-scss commands (if needed for that dev session), which is working pretty well for me.
Great, thanks for sharing this solution. I didn't think about directly checking ng-packagr config options. Now I understand why you were using rimraf. It makes more sense ;).
I'm able to run the watchers together and everything seems to work fine. I use npm-run-all to run parallel watch tasks, but it probably works the same way concurrently works (I didn't take the time to check).
Great job, yeah npm-run-all is about the same as concurrently, I selected concurrently since it has wild card support to run bunch of jobs at same time. ✌️
Thanks @hughanderson4, the watch mode is working nicely for me now with the following code:
"scripts": { "clean": "rimraf "./dist/"", "scss-bundle": "scss-bundle -e "./projects/my-lib/src/lib/shared/styles/styles.scss" -d "./dist/my-lib/styles/styles.scss"", "watch-ts": "ng build --watch=true", "watch-scss": "cpx "./projects/my-lib/src/lib/shared/styles/**/" "./dist/my-lib/styles" --watch --verbose && scss-bundle",
"watch-assets": "cpx "./my-lib/src/assets/**/" "./dist/my-lib/assets" --watch --verbose", "watchAll": "npm run clean & concurrently "npm:watch-"" },
I have added " && scss-bundle" in the "watch-scss" command as "scss-bundle" was not being called anywhere in the code you posted.
However, i have 1 issue: The dist folder has 2 sub-directories: app, my-lib
the assets and styles are copied inside the my-lib directory after running "npm run watchAll". Now, how do i use the dist/my-lib\styles/_styles.scss in my application? I have made the application's styles.scss empty as i want all library specific global styles to go under my-lib/styles/_style.scss