Webpack - CSS 未应用
Webpack - CSS not applied
我决定试试 Webpack 2。我正在尝试捆绑 js 和 css。
问题是 CSS 没有应用页面上的元素(它存在于构建的文件中)。
这是应用结构:
app
|-styles.css
|-app.js
build
|-bundle.js
index.html
webpack 配置文件:
var path = require('path');
module.exports = {
entry: './app/app.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'build')
},
module: {
rules: [
{
test: /\.css$/,
use: 'css-loader'
}
]
}
}
index.html:
<html>
<head>
<script src="./build/bundle.js"></script>
</head>
<body>
<div class="abc"> hello </div>
</body>
app.js:
require('./styles.css');
console.log('js loaded!');
当我 运行 构建命令得到这个输出时:
[0] ./app/styles.css 240 bytes {0} [built] [1] ./~/css-loader/lib/css-base.js 1.51 kB {0} [built] [2] ./app/app.js 148 bytes {0} [built]
我还可以看到 css 包含在 bundle.js 文件中
exports.push([module.i, ".abc {\r\n width: 300px;\r\n height: 100px;\r\n background-color: red;\r\n}", ""]);
如果我在 html 中包含 css 文件,它工作正常,所以我猜 CSS 本身没有拼写错误。我花了很多时间试图弄明白。有什么我遗漏的吗?
您正在将 CSS 作为仅包含 css-loader
的字符串加载。您还需要 style-loader
,以便在导入时将 CSS 加载到 DOM。
use: [ 'style-loader', 'css-loader' ]
我决定试试 Webpack 2。我正在尝试捆绑 js 和 css。
问题是 CSS 没有应用页面上的元素(它存在于构建的文件中)。
这是应用结构:
app
|-styles.css
|-app.js
build
|-bundle.js
index.html
webpack 配置文件:
var path = require('path');
module.exports = {
entry: './app/app.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'build')
},
module: {
rules: [
{
test: /\.css$/,
use: 'css-loader'
}
]
}
}
index.html:
<html>
<head>
<script src="./build/bundle.js"></script>
</head>
<body>
<div class="abc"> hello </div>
</body>
app.js:
require('./styles.css');
console.log('js loaded!');
当我 运行 构建命令得到这个输出时:
[0] ./app/styles.css 240 bytes {0} [built] [1] ./~/css-loader/lib/css-base.js 1.51 kB {0} [built] [2] ./app/app.js 148 bytes {0} [built]
我还可以看到 css 包含在 bundle.js 文件中
exports.push([module.i, ".abc {\r\n width: 300px;\r\n height: 100px;\r\n background-color: red;\r\n}", ""]);
如果我在 html 中包含 css 文件,它工作正常,所以我猜 CSS 本身没有拼写错误。我花了很多时间试图弄明白。有什么我遗漏的吗?
您正在将 CSS 作为仅包含 css-loader
的字符串加载。您还需要 style-loader
,以便在导入时将 CSS 加载到 DOM。
use: [ 'style-loader', 'css-loader' ]