我花了几个小时尝试让我的 Webpack 配置来编译 Sass;这有点荒谬。在我的研究过程中,我发现了数十个 Github 问题、Stackoverflow 帖子和博客讨论如何将 Sass 与 Webpack 结合使用,而且它们的做法都不同。而且,有很多问题的人。我只是认为 Webpack 需要更好地记录。呃。
我弄清楚了如何编译 Sass 并让 Webpack 在内存中从 /static
中提供它,但我希望类名具有本地作用域。这不是带有 React 组件的模块化 CSS 的好处之一吗?
本地范围示例:.foo__container___uZbLx {...}
所以,这是我的 Webpack 配置文件:
const webpack = require('webpack');
const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
devtool: 'source-map',
entry: {
bundle: './src/js/app'
},
output: {
path: __dirname,
filename: '[name].js',
publicPath: '/static'
},
plugins: [
new webpack.optimize.OccurrenceOrderPlugin(),
new ExtractTextPlugin('[name].css', {allChunks: true})
],
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
include: path.join(__dirname, 'src'),
loader: 'babel'
},
{
test: /\.scss$/,
exclude: /node_modules/,
include: path.join(__dirname, 'src'),
loader: ExtractTextPlugin.extract('style', 'css?sourceMap!sass')
}
]
}
};
我设法让它适用于普通 CSS:
{
test: /\.css$/,
exclude: /node_modules/,
include: path.join(__dirname, 'src'),
loader: ExtractTextPlugin.extract('style', 'css?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]')
}
我不太理解带有所有 ?
标记的类似参数的语法,并且我不知道要搜索什么来查找与之相关的文档。
这就是我的 React 组件的样子;万一您想看看我如何导入样式:
import React, { Component } from 'react';
import s from './foo.css';
class Foo extends Component {
render() {
return (
<div className={s.container}>
<h1 className="title">Welcome!</h1>
<p className="body">This is a dummy component for demonstration purposes.</p>
</div>
);
}
}
export default Foo;
另外,我还有三个不相关的问题:
- 如果 Webpack 仅通过
/static
从内存中提供文件,那么output.path
属性有何意义? - 如果我在这里所做的事情足够了,那么
webpack-dev-server
的意义何在?根据我的理解,webpack-dev-server
只是用于热模块替换的东西,对吗?只是自动刷新? - 我的
exclude
和include
属性是否多余?根据我的理解,排除node_modules
会减少编译时间,使其运行更快;需要处理的文件更少。
最佳答案
我让它与这个一起工作:
loader: ExtractTextPlugin.extract('style', 'css?modules&localIdentName=[name]__[local]___[hash:base64:5]!sass')
我所要做的就是将 !sass
放在查询末尾。我希望这些东西能得到更好的记录;在任何地方都找不到足够的文档...
关于javascript - 使用 Webpack 编译 Sass(和本地范围类名),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39717136/