Webpack scss& css模块反应 - 意外的令牌字符串

时间:2017-12-17 17:00:53

标签: css reactjs webpack sass css-modules

我尝试使用scss(mixins,变量等)和css模块的组合设置一个项目。

然而,当我使用style-loader,css-loader,postcss-loader,sass-loader,sass-resources-loader,import-glob-loader设置webpack时。我收到以下错误:

In [133]: a = np.asmatrix(np.random.randn(200,10000))

In [134]: %%timeit
     ...: col0_avg = (a[:,0,None] + 1)/2
     ...: avg = (a[:,1:] + a[:,:-1])/2
     ...: out0 = np.c_[col0_avg, avg]
100 loops, best of 3: 7.3 ms per loop

In [135]: %%timeit
     ...: out = a.copy()
     ...: out[:,1:] += a[:,:-1]
     ...: out[:,0] += 1
     ...: out /= 2
100 loops, best of 3: 5.22 ms per loop

In [152]: %timeit unif1d(a,size=2, axis=1, mode='constant', cval=1.0)
100 loops, best of 3: 6.71 ms per loop

Webpack Scss

Worker error  Error: Unexpected token string «./node_modules/css-   
 loader/index.js?"importLoaders":1,"modules":true,"localIdentName" 
 :"[name]__[local]___[hash:base64:5]"!./node_modules/postcss-loade 
 r/lib/index.js?!./node_modules/sass-loader/lib/loader.js!./node_m 
 odules/sass-resources-loader/lib/loader.js?"resources":["/Users/* 
 ***/Documents/Repos/project/src/scss/*.scss"]!./node_modules/impo 
 rt-glob-loader/index.js!./src/App/App.scss», expected punc «,»    
     at objectToError (/Users/****/Documents/Repos/project/node_mo 
 dules/workerpool/lib/WorkerHandler.js:63:14)                      
     at ChildProcess.<anonymous> (/Users/****/Documents/Repos/ui- 
 kit/node_modules/workerpool/lib/WorkerHandler.js:146:32)          
     at emitTwo (events.js:125:13)                                 
     at ChildProcess.emit (events.js:213:7)                        
     at emit (internal/child_process.js:774:12)                    
     at _combinedTickCallback (internal/process/next_tick.js:141:1 
 1)                                                                
     at process._tickCallback (internal/process/next_tick.js:180:9 
 ) filename: '0', line: 18, col: 936, pos: 2292     

反应:

const webpack = require('webpack');
const path = require('path');

const DashboardPlugin = require('webpack-dashboard/plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const autoprefixer = require('autoprefixer');

const nodeEnv = process.env.NODE_ENV || 'development';
const isProduction = nodeEnv === 'production';

const jsSrcPath = path.join(__dirname, './');
const publicPath = path.join(__dirname, './public');
const imgPath = path.join(__dirname, './src/assets/img');
const srcPath = path.join(__dirname, './src');

/* Common plugins */

const plugins = [
    new webpack.DefinePlugin({
        'process.env': {
            NODE_ENV: JSON.stringify(nodeEnv)
        }
    }),
    new webpack.NamedModulesPlugin(),
    new HtmlWebpackPlugin({
        template: path.join(publicPath, 'index.html'),
        path: publicPath,
        filename: 'index.html',
    }),
    new webpack.NoEmitOnErrorsPlugin(),
];

/* Common Rules */
const rules = [{
        test: /\.(js|jsx)$/,
        include: path.join(__dirname, 'src'),
        exclude: path.resolve(__dirname, "node_modules"),
        loader: "babel-loader"
    },
    {
        test: /\.scss$/,
        use: [
            'style-loader',
            {
                loader: 'css-loader',
                options: {
                  importLoaders: 1,
                  modules: true,
                  localIdentName: "[name]__[local]___[hash:base64:5]"
                }
            },
            {
                loader: 'postcss-loader',
                options: {
                    plugins: () => [autoprefixer]
                }
            },
            'sass-loader',
            {
                loader: 'sass-resources-loader',
                options: {
                    resources: [
                        path.resolve(__dirname, "./src/scss/*.scss")
                    ]
                }
            },
            'import-glob-loader'
        ]
    },
    {
        test: /\.woff$/,
        loader: "url-loader?limit=10000&mimetype=application/font-woff&name=[path][name].[ext]"
    }, {
        test: /\.woff2$/,
        loader: "url-loader?limit=10000&mimetype=application/font-woff2&name=[path][name].[ext]"
    },
    {
        test: /\.(png|gif|jpg|svg)$/,
        include: imgPath,
        use: 'url-loader?limit=20480&name=assets/[name]-[hash].[ext]',
    }
];

if (isProduction) {
    // Production plugins
    plugins.push(
        new webpack.LoaderOptionsPlugin({
            minimize: true,
            debug: false,
        }),
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false,
                screw_ie8: true,
                conditionals: true,
                unused: true,
                comparisons: true,
                sequences: true,
                dead_code: true,
                evaluate: true,
                if_return: true,
                join_vars: true,
            },
            output: {
                comments: false,
            },
        }),
    );

    // Production rules

} else {
    // Development plugins
    plugins.push(
        new webpack.HotModuleReplacementPlugin(),
        new DashboardPlugin()
    );
    // Development rules

}

module.exports = {
    devtool: isProduction ? 'eval' : 'source-map',
    context: jsSrcPath,
    entry: [
        'babel-polyfill',
        './src/index.js'
    ],
    output: {
        path: publicPath,
        publicPath: '/',
        filename: 'app-[hash].js',
    },
    module: {
        rules,
    },
    resolve: {
        extensions: ['.webpack-loader.js', '.web-loader.js', '.loader.js', '.js', '.jsx'],
        modules: [
            path.resolve(__dirname, "node_modules"),
            jsSrcPath
        ]
    },
    plugins,
    devServer: {
        contentBase: isProduction ? './public' : './src',
        historyApiFallback: true,
        port: 3000,
        compress: isProduction,
        inline: !isProduction,
        hot: !isProduction,
        host: '0.0.0.0',
        stats: {
            assets: true,
            children: false,
            chunks: false,
            hash: false,
            modules: false,
            publicPath: false,
            timings: true,
            version: false,
            warnings: true,
            colors: {
                green: '\u001b[32m'
            }
        }
    }
};

App.scss文件

import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'

import styles from './App.scss';

class App extends Component {
  render() {
    return (
      <div>
        <h1 className={styles.main}>Hello World</h1>
      </div>
    )
  }
}

const mapStateToProps = (state) => {
    return {
        app: state.app
    };
};

export default connect(mapStateToProps, null)(App)

其他人之前有过这个问题吗?

3 个答案:

答案 0 :(得分:1)

您的exclude: path.resolve(__dirname, "node_modules"),似乎受到指责。你可以尝试从装载机中删除它吗?

为您提供更多信息:错误报告了node_modules/css-loader/index.js的内容。一个java脚本文件。在js|jsx规则(即babel-loader)中,您完全排除了node_modules。这是问题的原因。

更新:发出原因代码

答案 1 :(得分:0)

Full for reference

  module: {
    rules: [
        {
            test: /\.js$/,
            exclude: /node_modules/,
            loader: 'babel-loader',
        },

        {
            test: /\.scss$/,
            loader: ExtractPlugin.extract(['css-loader', 'sass-loader']),
        },
        {
            test: /\.css$/,
            exclude: [/\.global\./, /node_modules/],
            loader: ExtractPlugin.extract(
                {
                    fallback: 'style-loader',
                    use: [
                        {
                            loader: 'css-loader',
                            options: {
                                importLoaders: 1,
                                modules: true,
                                autoprefixer: true,
                                minimize: true,
                                localIdentName: '[name]__[local]___[hash:base64:5]'
                            }
                        }
                    ]
                })
        },

答案 2 :(得分:0)

仍然没有100%确定为什么会这样,但我添加了extract-text-plugin并修复了我的问题。

{
  "Foo": {
    "Item1": true,
    "Item2": ["a", "b", "c"],
    "Item3": {
      "Baz": {
        "BazData1": false,
        "BazData2": "BlahBlahBlah"
      },
      "BazBaz": 2
    }
  },
  "Bar": {
    "Item1": false,
    "Item2": ["x", "y", "z"],
    "Item3": {
      "Baz": {
        "BazData1": true,
        "BazData2": "Tick Tock"
      },
      "BazBaz": 4
    }
  },
  "Bonk": "Boom"
}

还将for(String camera_id : cameraManager.getCameraIdList()){ Log.d(TAG, "Available Cameras: id: " + camera_id + " and rear facing = " + (cameraManager.getCameraCharacteristics(camera_id).get(CameraCharacteristics.LENS_FACING) == CameraCharacteristics.LENS_FACING_BACK)); } 添加到插件