从 Webpack 的“ node_module”导入 CSS

我使用的一些第三方模块有自己的 CSS 文件。我想把它们包括在我的应用程序的一个,单一的 CSS 文件,这是由 Webpack 处理。如何将“ node _ module”下的 CSS 文件导入到我的 CSS 文件中?

例如,我正在使用第三方 react-select模块,但是我不能从 node_modules导入它的 CSS 文件:

@import 'react-select/dist/react-datetime.css';

webpack.config.js中的相关装载机:

  {
test: /\.css$/,
use: ExtractTextPlugin.extract({
use: [
{
loader: 'css-loader',
options: {
url: false
}
}
]
})
}
90635 次浏览

You can import files relative to your project's root (resolving node_modules/ from the root folder) by prefixing with a tilde ~:

@import '~react-select/dist/react-datetime.css';

This is a poorly documented Webpack (a redundant phrase) convention, see https://github.com/webpack-contrib/css-loader/issues/12#issuecomment-41940311 and What does a `~` tilde in a CSS `url()` do?

If you are using too many things from one node_modules folder you can also create an alias by passing this following option

options: {
url: false,
includePaths: [
// this one for using node_modules as a base folder
path.resolve('node_modules'),
// this one for using sass as the base folder
path.resolve('node_modules/flag-icon-css/sass')
]
}

After the configuration, you can import as you were trying in your question.

I had a similar issue today. After all, all I had to do was to configure resolve in my webpack config file. I hope this will help somebody.

Webpack version I used:

"webpack": "^4.37.0",

In a webpack config file, the following should be configured:

module.exports = {
resolve: {
extensions: ['.json', '.js', '.jsx'],
modules: ['node_modules'],
},

or

module.exports = {
resolve: {
alias: {
'some-library': path.resolve(__dirname, './node_modules/some-library'),
}
},

In a css file, we can access a library by a relative path from node_modules:

@import '~some-library/src/some-css-file';