astroturfcss / astroturf

Better Styling through Compiling: CSS-in-JS for those that want it all.
https://astroturfcss.github.io/astroturf/
MIT License
2.28k stars 60 forks source link

Add style-loader 2.0 support #661

Open ai opened 3 years ago

ai commented 3 years ago

style-loader 2.0 now returns ES module and breaks Astroturf’s require()


Right now code like:

const styles = css`
  .button {
    color: black;
    border: 1px solid black;
    background-color: white;
  }
`

console.log(styles.button)

will be compiled by astroturf/loader to:

const styles = require('./index-styles.astroturf.pcss')

console.log(styles)

But webpack 4 will return ESM module on .astroturf.pcss import:

{
  __esModule: true
  default: {
    button: "index-styles-astroturf_button-9b607"
  }
}

As the result, styled doesn’t work because it expects to get { cls1, cls2 } from require but gets { __esModule: true, … }

Details

module.exports = {
  mode: IS_PRODUCTION ? 'production' : 'development',
  devtool: IS_PRODUCTION ? false : 'eval-cheap-module-source-map',
  entry: {
    app: join(__dirname, 'src', 'index.tsx')
  },
  output: {
    publicPath: '/',
    filename: '[name].[hash:8].js',
    chunkFilename: '[name]-[id].[hash:8].js'
  },
  devServer: {
    hot: true,
    open: true
  },
  plugins,
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: [
          {
            loader: 'babel-loader'
          },
          {
            loader: 'astroturf/loader',
            options: {
              extension: '.astroturf.pcss'
            }
          }
        ]
      },
      {
        test: /\.astroturf\.pcss$/,
        use: [
          IS_PRODUCTION ? MiniCssExtractPlugin.loader : 'style-loader',
          {
            loader: 'css-loader',
            options: {
              importLoaders: 1,
              modules: true
            }
          },
          {
            loader: 'postcss-loader'
          }
        ]
      }
    ]
  }
}

Possible solutions

  1. Move to import
  2. Add { __esModule: true, … } unwrapper
jquense commented 3 years ago

I have esm support in the v1 branch, we should probably back port if it's not too much trouble

ai commented 3 years ago

It will be great and improve onboarding

avionbg commented 3 years ago

Another solution is to just turn off the esModule with style-loader option like this: { loader: 'style-loader', options: { esModule: false, } },

btw. MiniCssExtractPlugin has also that option in case you hit the same issue with production build..