首页 文章

SASS不在React / Webpack项目中呈现

提问于
浏览
0

我在我的项目中添加了SASS,因为我喜欢在我的CSS中使用SASS . 在我的app文件夹中,我创建了CSS文件夹和一个SCSS文件夹 . 我运行sass --watch scss:css将我的scss更改映射到css文件夹 . 我认为这很有效 . 在我的webpack中,我添加了一个处理SCSS和SASS的加载器,并将所需的文件添加到我的package.json中 . 为了开始使用SASS样式,我是否需要将它们包含在我的index.html文件中,还是需要将它们导入到我想要使用来自'xpath'的新es6 import x的每个组件中?

这是我的package.json和webpack.config.js文件

{
  "name": "newaccount",
  "version": "1.0.0",
  "description": "a form submission for new accounts",
  "main": "App.js",
  "scripts": {
    "start": "webpack-dev-server"
  },
  "author": "---",
  "license": "ISC",
  "dependencies": {
    "react": "^15.4.1",
    "react-dom": "^15.4.1",
    "react-hot-loader": "^1.3.1",
    "react-router": "^3.0.0"
  },
  "devDependencies": {
    "babel-core": "^6.18.2",
    "babel-loader": "^6.2.8",
    "babel-preset-es2015": "^6.18.0",
    "babel-preset-react": "^6.16.0",
    "css-loader": "^0.26.1",
    "html-webpack-plugin": "^2.24.1",
    "node-sass": "^3.13.0",
    "sass": "^0.5.0",
    "sass-loader": "^4.0.2",
    "style-loader": "^0.13.1",
    "webpack": "^1.13.3",
    "webpack-dev-server": "^1.16.2"
  }
}

webpack.config.js

var HtmlWebpackPlugin = require('html-webpack-plugin');
var path = require('path');


var HTMLWebpackPluginConfig = new HtmlWebpackPlugin({
  template: __dirname + '/app/index.html',
  filename: 'index.html',
  inject: 'body'
});

module.exports = {
  entry: [
    './app/App.js'
  ],
  output: {
    path: __dirname + '/public',
    filename: "index_bundle.js"
  },
  plugins: [HTMLWebpackPluginConfig],
  devServer: {
       inline:true,
       contentBase: './public',
       port: 3333
     },
  module: {
    loaders: [{ 
         test: /\.js$/, 
         exclude: /node_modules/, 
         loader: "babel-loader"
      }, {
          test: /\.scss$/,
          include: path.join(__dirname, "app"),
          loaders: ["style", "css", "sass"]
        },
        {
              test: /\.scss$/,
              loader: 'style!css!sass'
            }]
  }
};

我的文件结构基本上是一个app文件夹和一个公用文件夹 . 在内部应用程序中,您有组件/容器/ css / scss / utils,而在public内部则是bundle.js和index.html文件 .

2 回答

  • 0

    您不应该在Webpack中使用外部Sass命令 . 您需要将Sass内容放在Webpack的依赖关系图中 . 为此,请告诉Webpack您正在使用 require() 完成的文件 . 在需要样式的页面的Javascript文件的顶部,添加

    require('./path/to/sass/scss')

    在开发模式下,这会将您的Sass代码转换为Javascript,将构建的CSS规则注入页面 . 我知道这很奇怪,但它可以让你热重新加载样式 . 您还应该使用ExtractTextPlugin单独生成构建Webpack配置,将构建的CSS拉出到单独的文件中,并将该文件加载到 生产环境 HTML中 .

    进一步阅读:Webpack: When to Use and Why .

  • 1

    我的webpack.config.js文件正在加载scss和sass两次,将其更改为

    {
         test: /\.scss$/,
         loader: 'style!css!sass'
    }]
    

    通过去除

    {
         test: /\.scss$/,
         include: path.join(__dirname, "app"),
         loaders: ["style", "css", "sass"]
     },
    

    现在我可以将我的SASS文件包含在我的反应组件中 . 现在我需要弄清楚如何在我的SASS文件中访问我的图像 - 似乎抛出质量错误=(

相关问题