我正在尝试将我的css包含在webpack-dev-server托管的服务器中。为了实现这一点,我显然必须一起使用style-loader和css-loader,以便将css捆绑到JavaScript中。
我无法让它发挥作用。
我按照说明here,但我收到以下错误:
> ./src/index2.js中的错误未找到模块:错误:无法在C:\ Users \ magnusga \ Downloads \ Programming \ TestPrograms \ test \ src'中解析' main.css '
@ ./src/index2.js 1:0-27
@ multi(webpack)-dev-server / client?http://localhost:8080 ./src/index2.js
我确定main.css
与index2.js
index2.js
import css from 'main.css';
// ...much more code
webpack.config.js
module.exports = {
entry: {
app: './src/index2.js'
},
devtool: 'inline-source-map',
devServer: {
contentBase: './dist'
},
module: {
rules: [
{
test: /\.css$/,
exclude: /node_modules/,
use: ['style-loader', 'css-loader']
}
],
},
plugins: [
new CleanWebpackPlugin(['dist']),
new HtmlWebpackPlugin({
title: 'Development',
template: 'src/index.html',
inject: 'head'
})
],
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
}
};
的package.json
{
"name": "test",
"version": "1.0.0",
"description": "",
"main": "index2.js",
"dependencies": {
"rxjs": "^5.5.6"
},
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-env": "^1.6.1",
"clean-webpack-plugin": "^0.1.17",
"css-loader": "^0.28.11",
"extract-text-webpack-plugin": "^3.0.2",
"html-webpack-plugin": "^2.30.1",
"postcss-loader": "^2.1.3",
"sass-loader": "^6.0.7",
"style-loader": "^0.20.3",
"webpack": "^3.10.0",
"webpack-dev-server": "^2.11.0"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"buildb": "babel src --watch --out-dir built --copy-files",
"watch": "webpack --watch",
"start": "webpack-dev-server",
"build": "webpack"
},
"author": "",
"license": "ISC"
}
一种解决方法是使用import css from './main.css';
代替import css from 'main.css';
(请注意文件名前面的./
)。
虽然感觉不对,因为css-loader site表明它应该是后者,而不是前者。
这是文档中的拼写错误吗?
谢谢。
答案 0 :(得分:2)
这不是一个错字。如果你这样导入它:
import css from 'main.css';
Webpack认为,您要导入模块,并在node_modules下搜索此文件。这是必要的,例如,当你安装了bootstrap包并想要导入它的css时。因此,当您的css文件来自依赖项时,您可以像这样导入该依赖项。但是当您想要导入lokal文件时,请始终使用相对路径。
所以必须是:import css from './main.css';
进一步阅读: