Giter Club home page Giter Club logo

lit-scss-loader's Introduction

It is a fork of polymer-css-loader! But since the loader was only developed for polymer, I adopted it for lit-element, now lit.

lit-scss-loader

A loader for webpack that lets you import the CSS/SCSS into your lit-element and automatically creates the styling JavaScript for you.

While this loader has worked well on my Windows machine, there may still be unforeseen bugs. Even though I put the package to v1.0 be cautious when using it in production.

Install:

npm i -D lit-scss-loader extract-loader

Requirements

  • Lit
  • Webpack 4/5 ('extract-loader', 'css-loader', 'sass-loader')

How this works:

  1. Include it in your Webpack Config. Include it "last" (webpack loader order!) or after all other loaders have been applied. You will need to use extract-loader if you're using sass-loader, less-loader and/or css-loader
module.exports = {
    entry: './src/index.js',
    module: {
        rules: [
            {
                test: /\.css|\.s(c|a)ss$/,
                use: [{
                    loader: 'lit-scss-loader',
                    options: {
                        minify: true, // defaults to false
                    },
                }, 'extract-loader', 'css-loader', 'sass-loader'],
            },
        ],
    },
};
  1. Include your .css or .scss or .less file in your JavaScript:
import {html, LitElement} from 'lit';

import Style1 from './style-1.scss';
import Style2 from './style-2.css';

class LitTestComponent extends LitElement {

    constructor() {
        super();
        this.prop1 = 'πŸ”₯-app';
    }

    static get properties() {
        return {
            prop1: {
                type: String
            }
        };
    }

    static get styles() {
        return [Style1, Style2];
    }

    render() {
        return html`
           <p>This is the test component</p>
           <p>This is the propertie's value: ${this.prop1} </p>
           <div id="test">This font size should be bigger</div>
    `;
    }
}

customElements.define('lit-test-component', LitTestComponent);

Typescript

If you're using this loader in a Typescript project, you will also need to inform the compiler that it has the ability to load CSS/SCSS files. This project already provides the module declarations, so all you need to do is include the type declaration file in your tsconfig.json file.

{
  "compilerOptions": {
    "...": "..."
  },
  "include": [
    "node_modules/lit-scss-loader/types.d.ts"
  ]
}

Options

Name Type Default Description
minify {Boolean} false When true, it will minify both the CSS and JavaScript output.
defaultSkip {Boolean} false (dep.) When true, will skip all imports except those explicilty marked.

Files Parameters (obsolete)

These were applicable when using Polymer 3. With lit, everything is better.

They are appended at the end of the CSS imports in your JavaScript file (Where the component is declared); E.g:

import './style-2.css?include';
import './style-1.css?skip';
Name Type Default Description
skip {boolean} N/A Setting this parameter will skip the import altogether. This may be useful if you're using React and Lit or you'd like to include the CSS without. E.g: import './style-2.css?skip'
include {boolean} N/A Just setting this parameter will include the css even when defaultSkip is on. This may be useful if you just want to "litify" or "web-componentize" a .css/.scss/.less file. E.g: import './style-2.css?include'. Note: include will take preference over skip.

Need an example?

First build lit-scss-loader with npm run build inside the root, then navigate to test-app and execute: npm start. It will launch an express server @ localhost:3000.

Legacy Support

The loader automatically injects code (e.g. import {css} from 'lit';) into your files, therefore, pay attention if you need es5 / legacy browsers support. As LambyPants mentioned, you might have to adopt your loaders configuration to also test for /\.js$|\.ts$|\.s(c|a)ss$/ and transform it to your needed language support.

Why this loader?

When using css for components inline or inside a javascript file we will lose auto-completion or any analysis tools that are already out there for plain CSS/SCSS files. Also, designer may don't want to work inside .js files. Let them work with what they are used to.

With this, you just import your .css in your lit-component, add the style-variable to the static get styles() and you're set! The loader takes care for creating the content of that variable!

Ideas? Feedback?

Open a GitHub issue now! 😊

lit-scss-loader's People

Contributors

dependabot[bot] avatar drdreo avatar halbekanne avatar jonahbron avatar krispy1298 avatar pkmnplatin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

lit-scss-loader's Issues

Typescript Compiler

When using the basic instructions with a Typescript project, tsc will complain:

TS2307: Cannot find module './style.scss' or its corresponding type declarations.

This is because Typescript doesn't think it can load SCSS files (even though Webpack makes that possible). It's necessary to trick Typescript into not complaining. This can be done by

  1. Adding a global.d.ts file (or any declaration file really) like so:
declare module '*.scss';
  1. Including it in tsconfig (don't import)
{
  "compilerOptions": {
    ...
  },
  "include": [
    "path/to/global.d.ts"
  ]
}

With that in place it should work properly.

Source: https://stackoverflow.com/a/41946697/278899

MIME Issue

Hi there,
thank you so much for this great plugin. Everything works fine when developing components with lit-element and scss. I'd love to make use of storybook.js. When I start and build the storybook, an error says that SCSS can't be imported as a javascript module.

Failed to load module script: The server responded with a non-JavaScript MIME type of "text/x-scss". Strict MIME type checking is enforced for module scripts per HTML spec.

My components import the SCSS like so:

import MwButtonStyles from './_mw-button.scss';

export class MwButton extends LitElement {
  static get styles() {
      return [ MwButtonStyles ]
  }

I even tried to do stuff like this in a _mw-button.js which I've imported to the lit-component then:

import MwButtonStyles from './_mw-button.scss';

export default MwButtonStyles;

and then import it again… but it doesn't work either for the same reason.

Do you have any pointers?

Thank you!

NPM package

Are you planning on publishing it as an NPM in the nearest time? Thanks for this!

Plans to support Webpack 5?

Hi there, it's a wonderful solution to include SCSS files into LitElement.

Are there any plans on supporting Webpack 5 in the future?

NPM release

Is there an NPM release anytime soon? There is pretty much a very old version on NPM with wrong commands. And the readMe on Github is much sweeter as well.

Warning with new Lit

With the new Lit I'm getting The main 'lit-element' module entrypoint is deprecated. Please update your imports to use the 'lit' package: 'lit' and 'lit/decorators.ts' or import from 'lit-element/lit-element.ts'. warning.

To update to new lit I have this in my package.json:

"lit": "^2.0.0-rc.1", "lit-element": "^3.0.0-rc.1",

webpack configuration problems

Hi there,
I already had a couple of SCSS loader rules defined in my webpack.config.js and wanted to install lit-scss-loader. This was the original file:
const HtmlWebPackPlugin = require("html-webpack-plugin");

module.exports = {
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: {
                    loader: "babel-loader"
                }
            },
            {
                test: /\.html$/,
                use: [
                    {
                        loader: "html-loader",
                        options: { minimize: true }
                    }
                ]
            },
            {
                test: /\.(scss)$/,
                use: [{
                    loader: 'style-loader', // inject CSS to page
                }, {
                    loader: 'css-loader', // translates CSS into CommonJS modules
                }, {
                    loader: 'postcss-loader', // Run post css actions
                }, {
                    loader: 'sass-loader' // compiles Sass to CSS
                }]
            },
            {
                test: /\.(png|svg|jpg|gif)$/,
                use: [
                    'file-loader',
                ],
            },
            {
                test: /\.(woff|woff2|eot|ttf|otf)$/,
                use: [
                    'file-loader',
                ],
            },
        ]
    },
    plugins: [
        new HtmlWebPackPlugin( {
            template: "./src/index.html",
            filename: "./index.html"
        }),
    ]
}

Then I added the following block below (that's how I've understood your instructions):

{
        test: /\.css|\.s(c|a)ss$/,
        use: [{
          loader: 'lit-scss-loader',
          options: {
            minify: true, // defaults to false
          },
        }, 'extract-loader', 'css-loader', 'sass-loader'],
      },

And now I'm getting the following error:

Module build failed (from ./node_modules/sass-loader/dist/cjs.js):
SassError: property "css" must be followed by a ':'
        on line 1 of src/styles/main.scss
>> import {css} from 'lit-element'; export default css`@import url(https://font
   --------^

 @ ./src/styles/main.scss 2:26-390
 @ ./src/index.js

I think I misconfigured webpack and these SCSS rules need to be merged somehow. But I have no idea how. Can I kindly ask you for some pointers? :-)

Thank you!

Minify option true, remove css svg properties

Setting up minify option to true removing svg properties cx, cy, r.

I think this behaviour coming from clean-css@v4 package

var CleanCSS = require('clean-css');
var input = `
  .test {
    cx: 0.5em;
    cy: 0.5em;
    fill: none;
    r: 0.2em;
  }
`;
var options = { /* options */ };
var output = new CleanCSS(options).minify(input);

console.log(output.styles);

By changing it to clean-css version 5, should fix this issue

Include documentation for use in es5 / legacy browsers

Hi,

Really like this package - it made our lives much easier when looking support scss in lit. Thanks for your contribution!

Just a suggestion, as I recently spent a few hours trying to add ie11 support to a lit-based project; ended up discovering it was the extract-loader in this package which was converting scss -> js and was being ignored by our babel-loader. It was particularly confusing because older browsers give no context to the error and just shows a lit-element css.ts file (which I assume is being imported in templateGenerator.js via generateCSSImport) as being the cause of the issue.

Normally your babel-loader config looks something like this:

    module: {
      rules: [
        {
          test: /\.js$|\.ts$/,
          use: {
            loader: 'babel-loader',
....

Was able to resolve the issue by simply doing the following

    module: {
      rules: [
        {
          test: /\.js$|\.ts$|\.s(c|a)ss$/,
          use: {
            loader: 'babel-loader',

There might be other ways to do this, but it def could save future users some time if they are using with tools like babel. Thanks!

template literal breaks IE11

import {css} from 'lit-element'; export default css`:host{...}`

The backticks cause an error IE11. Would it be possible to use quotes here?

The 1.1.0 release breaks builds because of webpack 5

Requiring webpack 5 instead of webpack 4 was a breaking change. It should be accompanied by increasing the major version and not the minor. Projects depending on ^1.0.0 of lit-css-loader got broken unexpectedly, when you rele3ased 1.1.0. Many other projects did the upgrade to webpack 5 properly (copy-webpack-plugin, css-loader, sass-loader, style-loader, ...).

How about fixing the problem by retaining the webpack 4 support in the 1.x releases and introducing the webpack 5 support in 2.x releases? For example:

1.1.1 - you could republish the 1.0.1 with the webpack 4 support to fix the 1.1.0
2.0.0 - you could republish the current 1.1.0 content as 2.0.0

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.