Home > Net >  import css file into es6 returns string instead of object
import css file into es6 returns string instead of object

Time:10-18

I'm importing a css file into a typescript module, but the import resolves to a string instead of an object. Can anyone tell me why I don't get an object??

// preview.ts

import test from './src/assets/test.theme.css'

console.log('typeof test: ', typeof test);
console.log(test);

Console output: (screenshot)

I know, adding an image would be nicer, however, I'm not allowed to do that, yet :(

typeof test: string
-------------------------------------------------------------------------------------------------
// Imports
import ___CSS_LOADER_API_SOURCEMAP_IMPORT___ from "../../../node_modules/css-loader/dist/runtime/cssWithMappingToString.js";
import ___CSS_LOADER_API_IMPORT___ from "../../../node_modules/css-loader/dist/runtime/api.js";
var ___CSS_LOADER_EXPORT___ = ___CSS_LOADER_API_IMPORT___(___CSS_LOADER_API_SOURCEMAP_IMPORT___);
// Module
___CSS_LOADER_EXPORT___.push([module.id, "body {\r\n  background-color: red;\r\n}\r\n", "",{"version":3,"sources":["webpack://./.storybook/src/assets/test.css"],"names":[],"mappings":"AAAA;EACE,qBAAqB;AACvB","sourcesContent":["body {\r\n  background-color: red;\r\n}\r\n"],"sourceRoot":""}]);
// Exports
export default ___CSS_LOADER_EXPORT___;
-------------------------------------------------------------------------------------------------

Environment:

  • Angular 12
  • Webpack 5

Webpack Config:

{
  rules: [
    {
      test: /\.(?:css)$/i,
      rules: [ 'css-loader' ]
    }
  ]
}

Reproduction

I was able to reproduce this issue with a basic Angular12 app, as described here: import test from "css-loader!./test.css" returns string

CodePudding user response:

As proposed by @Akxe, I tried using

import * as test from './src/assets/test.css'

This has solved my issue. Thanks again ;-)

CodePudding user response:

I think you have mistake in your Webpack config. You have nested rules property, instead you should have use:

{
    rules: [
      {
        test: /\.css$/i,
        use: ["style-loader", "css-loader"],
      },
    ],
  }

https://webpack.js.org/loaders/css-loader/

  • Related