问题
Some third-party modules I'm using have their own CSS files. I'd like to include them in my app's one, single CSS file, which is processed by Webpack. How can CSS files under "node_modules" be imported into my CSS file?
For example, I'm using the third-party react-select
module, but I can't import its CSS file from node_modules
:
@import 'react-select/dist/react-datetime.css';
The relevant loader in webpack.config.js
:
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
use: [
{
loader: 'css-loader',
options: {
url: false
}
}
]
})
}
回答1:
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?
回答2:
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.
来源:https://stackoverflow.com/questions/49518277/import-css-from-node-modules-in-webpack