import css from node_modules with webpack target node

1k Views Asked by At

I'm currently building a react app with server side rendering. I'm using some libraries that come with css files. When I try to import them like this:

import 'leaflet/dist/leaflet.css';

I get the following error in my server.js:

/my/app/path/node_modules/leaflet/dist/leaflet.css:3
.leaflet-pane,
^

SyntaxError: Unexpected token .
    at createScript (vm.js:74:10)
    at Object.runInThisContext (vm.js:116:10)
    at Module._compile (module.js:533:28)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:503:32)
    at tryModuleLoad (module.js:466:12)
    at Function.Module._load (module.js:458:3)
    at Module.require (module.js:513:17)
    at require (internal/module.js:11:18)
    at Object.__webpack_exports__.a (/my/app/path/server.js:725:18)

Importing with

import '../../node_modules/leaflet/dist/leaflet.css';

works.

Is there some way to configure webpack that I can import those css files normally?

Here's the webpack config for server.js:

const nodeExternals = require('webpack-node-externals');
const postcssImport = require('postcss-import');
const cssnext = require('postcss-cssnext');
const cssnano = require('cssnano');

module.exports = {
  entry: './src/server.js',
  output: {
    filename: 'server.js',
    path: __dirname,
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        options: {
          presets: [
            'react',
            ['env', {
              modules: false,
              targets: {
                node: process.versions.node,
              },
            }],
          ],
        },
      },
      {
        test: /\.css$/,
        use: [
          'css-loader',
          {
            loader: 'postcss-loader',
            options: {
              plugins: [
                postcssImport,
                cssnext,
                cssnano({
                  safe: true,
                  autoprefixer: false,
                }),
              ],
            },
          },
        ],
      },
      {
        test: /\.png$/,
        use: ['url-loader?limit=100000'],
      },
    ],
  },
  target: 'node',
  externals: [nodeExternals()],
};
1

There are 1 best solutions below

0
On BEST ANSWER

It is an issue of webpack-node-externals which prevents bundling all resources located under node_modules directory.

You can use the whitelist option to avoid this behavior.

Here is an example from documentation of webpack-node-externals:

...
nodeExternals({
   // load non-javascript files with extensions, presumably via loaders
   whitelist: [/\.(?!(?:jsx?|json)$).{1,5}$/i],
}),
...