使用webpack目标节点从node_modules导入css

时间:2017-09-05 09:33:41

标签: javascript node.js webpack serverside-rendering

我目前正在使用服务器端渲染构建反应应用。我使用了一些带有css文件的库。当我尝试像这样导入它们时:

import 'leaflet/dist/leaflet.css';

我的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)

使用

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

作品。

有没有办法配置webpack,我可以正常导入这些css文件?

这里是server.js

}的webpack配置
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 个答案:

答案 0 :(得分:3)

这是webpack-node-externals的问题,它阻止捆绑node_modules目录下的所有资源。

您可以使用whitelist选项来避免这种情况。

以下是webpack-node-externalsdocumentation的示例:

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