Search code examples
javascriptcssbundle

bundle css into one file


I would like to bundle multiple css files into 1 file. I have considered webpack but it from what documentation I have seen webpack's style requires you to bundle all your files html+css+js together which I can not due to my applications architecture.

Is there some way to bundle js and css without bundle the html as well? or rather bundling them independently.


Solution

  • You can use gulp

    Install dependencies:

    npm install --global gulp-cli
    npm install --save-dev gulp gulp-concat gulp-cssnano gulp-uglify
    

    Create gulpfile.js like this:

    const gulp = require('gulp');
    const concat = require('gulp-concat');
    const cssnano = require('gulp-cssnano');
    const uglify = require('gulp-uglify');
    
    gulp.task('bundle-css', () => {
        return gulp.src('css/*.css')
            .pipe(concat('bundle.css'))
            .pipe(cssnano())
            .pipe(gulp.dest('dist/css'));
    });
    
    gulp.task('bundle-js', () => {
        return gulp.src('js/*.js')
            .pipe(concat('bundle.js'))
            .pipe(uglify())
            .pipe(gulp.dest('dist/js'));
    });
    
    gulp.task('default', gulp.parallel('bundle-css', 'bundle-js'));
    
    

    To bundle both run:

    gulp
    

    To bundle by task run:

    gulp bundle-css
    gulp bundle-js