Module Import is a PostCSS plugin that inlines @import
statements as CSS
Modules in CSS, giving you all the modular benefits while also maintaining a
separation between style, markup, and functionality.
Module Import also supports sugary imports like Sass and automatically looks for stylesheets within npm and Bower packages. It can even generate files if they don’t already exist to further reduce development time.
/* before */
@import "module/_some-module";
@import "module/_another-module";
/* before: module/_some-module.css */
.container {
background-color: red;
}
/* before: module/another-module.css */
.container {
background-color: blue;
}
/* after */
._container_eosv8_1 {
background-color: red
}
._container_wpmzm_1 {
background-color: blue
}
Manifest JSON
{
"module/_some-module.css": {
"container": "_container_eosv8_1"
},
"module/_another-module.css": {
"container": "_container_wpmzm_1"
}
}
Now your modules are mixed into the same file while preserving access to their parts.
<?php
// get the path to the modules json
$css_modules_path = get_template_directory() . '/assets/css/theme.json';
// load the modules json
$css_modules = json_decode( file_get_contents( $css_modules_path ), true );
// get the modules names for a particular path
$article_cn = $css_modules[ 'module/_main-article.css' ];
?>
<article class="<?php echo esc_attr( $article_cn['container'] ); ?>">
<h1 class="<?php echo esc_attr( $article_cn['title'] ); ?>">My style is scoped.</h1>
</article>
Follow these steps to use Module Import.
Add Module Import to your build tool:
npm install postcss-module-import --save-dev
require('postcss-module-import')({ /* options */ }).process(YOUR_CSS);
Add PostCSS to your build tool:
npm install postcss --save-dev
Load Module Import as a PostCSS plugin:
postcss([
require('postcss-module-import')({ /* options */ })
]);
Add Gulp PostCSS to your build tool:
npm install gulp-postcss --save-dev
Enable Module Import within your Gulpfile:
var postcss = require('gulp-postcss');
gulp.task('css', function () {
return gulp.src('./css/src/*.css').pipe(
postcss([
require('postcss-module-import')({ /* options */ })
])
).pipe(
gulp.dest('./css')
);
});
Add Grunt PostCSS to your build tool:
npm install grunt-postcss --save-dev
Enable Module Import within your Gruntfile:
grunt.loadNpmTasks('grunt-postcss');
grunt.initConfig({
postcss: {
options: {
processors: [
require('postcss-module-import')({ /* options */ })
]
},
dist: {
src: 'css/*.css'
}
}
});
Type: Array
Default: []
A list of PostCSS plugins to run on each @import
before being processed by
CSS Modules.
Type: Array
Default: []
A list of PostCSS plugins to run on each @import
after being processed by
CSS Modules.
Type: Object
Default: {}
The options passed into the PostCSS Partial Import plugin.
Type: Object
Default: {}
The options passed into the PostCSS Modules plugin.