node.js - webpack 使用 webpack.config.js 文件失败“模块构建失败:未知单词”
问题描述
尝试使用 css-loader 添加 css 时,webpack 对我不起作用。
操作系统:Windows 10 pro,webpack:4.8.0 节点:8.9.4 npm:6.0.0 css-loader:0.28.11 style-loader:0.21.0
包.json
{
"name": "webpack-dev",
"version": "1.0.0",
"description": "",
"main": "index.php",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "./src/app.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^7.1.4",
"babel-preset-env": "^1.6.1",
"css-loader": "^0.28.11",
"extract-text-webpack-plugin": "^3.0.2",
"file-loader": "^1.1.11",
"node-sass": "^4.9.0",
"raw-loader": "^0.5.1",
"sass-loader": "^7.0.1",
"style-loader": "^0.21.0",
"url-loader": "^1.0.1",
"webpack": "^4.8.1",
"webpack-cli": "^2.1.3"
}
}
应用程序.js
require('./style.css');
require('./scripts.js');
错误信息
Version: webpack 4.8.1
Time: 2157ms
Built at: 2018-05-09 14:13:17
Asset Size Chunks Chunk Names
bundle.js 3.68 KiB main [emitted] main
Entrypoint main = bundle.js
[./src/app.js] 48 bytes {main} [built]
[./src/scripts.js] 28 bytes {main} [built]
[./src/style.css] 222 bytes {main} [built] [failed] [1 error]
ERROR in ./src/style.css
Module build failed: Unknown word (2:1)
1 |
> 2 | var content = require("!!./style.css");
| ^
3 |
4 | if(typeof content === 'string') content = [[module.id, content, '']];
5 |
@ ./src/app.js 1:0-22
样式.css
body {
color: red;
}
我只是使用命令webpack
,每次都失败。这是有史以来最令人沮丧的工具。除非我把!!
require 语句放在前面,否则什么都行不通,即require(!!'./style.css')
我已经阅读了我可以在 npm、stackoverflow 等上找到的所有关于此的错误报告,但似乎没有任何问题指向我的问题。我从字面上按照 webpack 模块部分的说明逐字进行了操作,但它仍然无法正常工作。请帮忙!
编辑:忘记配置文件
const webpack = require('webpack')
const path = require('path')
const config = {
entry: './src/app.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
mode: 'development',
module: {
rules: [
{
test: /\.(s*)css$/,
use: [
'sass-loader',
'css-loader',
'style-loader'
]
},
{
test: /\.js$/,
exclude: /(node_modules)/,
use: [
'babel-loader'
]
},
{
test: /\.(png|svg|jpg)$/,
use: [
'file-loader'
]
}
]
}
};
module.exports = config;
回答
原来顺序很重要
...
use: [
"style-loader",
"css-loader",
"sass-loader"
]
...
解决方案
在 webpack 中,当您在规则中列出多个加载器时,它们会从右到左进行评估(在您的情况下,从下到上),因此您的 scss 规则应该是:
{
test: /\.(s*)css$/,
use: [
'style-loader',
'css-loader',
'sass-loader'
]
}
原因是首先,您希望您的 sass 编译为 css,然后 css 将通过样式加载器内联到您的 html 文件中。
此外,如果您不使用 sass,则可以删除 sass-loader。
推荐阅读
- sass - sass @use 指令和移动优先方法
- android - 三星 Galaxy S10 的 Visual Studio AVD 设置
- android - 使用 Kotlin 从网站检索 HTML 代码
- c++ - 不同 GLIBC 版本的 Linux“交叉编译”
- c - 为什么这个 Visual Studio Code 只是运行而不给出输出?
- reactjs - 在选择框中获取 API 问题
- react-native - 如何使用按钮单击获取平面列表上的数据?
- java - 为什么在构建 docker 映像时突然 apk jdk11 安装停止工作?
- wordpress - Wordpress Single Sign On Client 免费插件可针对外部 OAuth2 服务器对用户进行身份验证
- python - 没有括号行为的Python多个'OR''AND'条件