Tomas Varga
Tomas Varga

Reputation: 1440

Importing css with webpack 3

I'm struggling with css import in a Webpack 3 (but tried even downgrading to 2.7) powered isomorphic react app - I need to import a css of an external library but cannot figure out how to distinguish client/server configuration for style-loader.

When importing the css like so:

import 'react-datepicker/dist/react-datepicker.css'

with suggested style-loader resp. css-loader config:

  module: {
    //...
    rules: [
      {
        test: /\.css$/,
        use: [ 'style-loader', 'postcss-loader' ]
      }
    ]

I'm receiving an error on the server (run by babel-node) suggesting the css is being imported as an ordinary JS module:

/.../node_modules/react-datepicker/dist/react-datepicker.css:1
(function (exports, require, module, __filename, __dirname) { .react-datepicker-popper[data-placement^="bottom"] .react-datepicker__triangle, .react-datepicker-popper[data-placement^="top"] .react-datepicker__triangle, .react-datepicker__year-read-view--down-arrow,
                                                              ^

SyntaxError: Unexpected token .
    at new Script (vm.js:51:7)
    at createScript (vm.js:138:10)
    at Object.runInThisContext (vm.js:199:10)
    at Module._compile (module.js:624:28)
    at Module._extensions..js (module.js:671:10)
    at Object.require.extensions.(anonymous function) [as .js] (/srv/lab/www/cosech/dev/node_modules/babel-register/lib/node.js:152:7)
    at Module.load (module.js:573:32)
    at tryModuleLoad (module.js:513:12)
    at Function.Module._load (module.js:505:3)
    at Module.require (module.js:604:17)

I thought the bundle created by webpack is usable on both the client and the server the same way (when not using brower-specific API) but it seems like it's not true; i tried isomorphic-style-loader instead but with the same results.

Does anyone know how to import css in the server/client scenario? (In the case of an external library I could just copy the css file into a public folder and link it the oldschool way in the index.html but I'd like to know how to do a proper css import so it's included in the bundle.)

Upvotes: 1

Views: 795

Answers (2)

Ru Chern Chong
Ru Chern Chong

Reputation: 3756

For CSS or stylesheets in general, use the @import syntax.

Using yours as an example,

@import '~react-datepicker/dist/react-datepicker.css';

The above will work assuming you are using npm packages.

Upvotes: 0

radhey shyam
radhey shyam

Reputation: 769

Try it like this.

import cssStype from 'react-datepicker/dist/react-datepicker.css'

Upvotes: 0

Related Questions