Importing CSS files as a string to JavaScript
npm install parcel-transformer-css-to-string


Importing CSS files as a string to JavaScript.
Transform plugin for Parcel v2
> Support Parcel v1: parcel-plugin-css-to-string
styles.inline.css
``css`
.text {
color: #000000;
}
index.js
`js
import styles from './styles.inline.css';
document.body.insertAdjacentHTML('beforeend', );`
Result:
`js`
document.body.insertAdjacentHTML("beforeend","");
//# sourceMappingURL=index.js.map
`bash`
npm i parcel-transformer-css-to-stringor
yarn add -D parcel-transformer-css-to-string
Add the plugin to transformers section in your .parcelrc.
In example use a Glob) pattern for *.inline.css files that will be inlined as a string into JavaScript.
.parcelrc
`json`
{
"extends": "@parcel/config-default",
"transformers": {
"*.inline.css": [
"parcel-transformer-css-to-string"
]
}
}
You can configure minify CSS in production build, where custom configuration can be set by creating cssnano.config.js file
cssnano.config.js
`js`
module.exports = {
preset: [
"default",
{
calc: false,
discardComments: {
removeAll: true,
},
},
],
}
You can configure CSS transforming with PostCSS creating a configuration file using one of these names (in that priority): .postcssrc (JSON), .postcssrc.json, .postcssrc.js, or postcss.config.js.
> If you use PostCSS config then you need added cssnano plugin to minify production build.
.postcssrc
`js`
{
"plugins": {
"postcss-import": {},
"autoprefixer": {},
"cssnano": {}
}
}
You can use official build-in named pipelines bundle-text:. In this case Parcel create a JavaScript module.
style.css
`css`
.text {
color: #000000;
}
index.js
`js
import styles from 'bundle-text:./styles.css';
document.body.insertAdjacentHTML('beforeend', );`
Reslut:
`js
function e(e){return e&&e.__esModule?e.default:e}document.body.insertAdjacentHTML("beforeend",);``
//# sourceMappingURL=index.js.map