尝试使用webpack和babel加载css时出现意外的令牌

时间:2017-04-22 13:00:05

标签: reactjs express webpack webpack-style-loader css-loader

我正在使用Express建立一个反应应用程序, 我尝试添加样式加载器/ css加载器以启用导入css, 但是当我启动我的服务器时,我收到以下错误:

M:\MainFiles\MyStuff\Code\react\FlexBoardToolBox>npm run start:dev

> flex_board@1.0.0 start:dev M:\MainFiles\MyStuff\Code\react\FlexBoardToolBox
> cross-env NODE_ENV=development && npm run build:dev && nodemon --exec babel-node -- src/server/server.js


> flex_board@1.0.0 build:dev M:\MainFiles\MyStuff\Code\react\FlexBoardToolBox
> webpack -d

Hash: 1b4953ee761d210e2488
Version: webpack 2.2.1
Time: 2567ms
    Asset     Size  Chunks                    Chunk Names
bundle.js  2.54 MB       0  [emitted]  [big]  js
   [6] ./~/react/react.js 55 bytes {0} [built]
  [23] ./~/react/lib/React.js 2.71 kB {0} [built]
  [24] ./~/react-router-dom/es/index.js 2.21 kB {0} [built]
  [89] ./~/react-router-dom/es/Link.js 4.67 kB {0} [built]
  [94] ./~/react-dom/index.js 58 bytes {0} [built]
 [195] ./~/react-router-dom/es/MemoryRouter.js 259 bytes {0} [built]
 [196] ./~/react-router-dom/es/NavLink.js 3.36 kB {0} [built]
 [197] ./~/react-router-dom/es/Prompt.js 253 bytes {0} [built]
 [198] ./~/react-router-dom/es/Redirect.js 255 bytes {0} [built]
 [199] ./~/react-router-dom/es/Route.js 252 bytes {0} [built]
 [201] ./~/react-router-dom/es/StaticRouter.js 259 bytes {0} [built]
 [202] ./~/react-router-dom/es/Switch.js 253 bytes {0} [built]
 [203] ./~/react-router-dom/es/matchPath.js 256 bytes {0} [built]
 [204] ./~/react-router-dom/es/withRouter.js 257 bytes {0} [built]
 [236] ./src/client/app-client.js 706 bytes {0} [built]
    + 222 hidden modules
[nodemon] 1.11.0
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `babel-node src/server/server.js`
M:\MainFiles\MyStuff\Code\react\FlexBoardToolBox\node_modules\babel-core\lib\transformation\file\index.js:590
      throw err;
      ^

SyntaxError: M:/MainFiles/MyStuff/Code/react/FlexBoardToolBox/src/client/components/Test/text.css: Unexpected token (1:0)
←[0m←[31m←[1m>←[22m←[39m←[90m 1 | ←[39m←[33m.←[39mtest{
 ←[90m   | ←[39m←[31m←[1m^←[22m←[39m
 ←[90m 2 | ←[39m    background←[33m:←[39m blue←[33m;←[39m
 ←[90m 3 | ←[39m    font←[33m-←[39msize←[33m:←[39m ←[35m1.234←[39mpx←[33m;←[39m
 ←[90m 4 | ←[39m} ←[0m
    at Parser.pp$5.raise (M:\MainFiles\MyStuff\Code\react\FlexBoardToolBox\node_modules\babylon\lib\index.js:4373:13)
    at Parser.pp.unexpected (M:\MainFiles\MyStuff\Code\react\FlexBoardToolBox\node_modules\babylon\lib\index.js:1716:8)
    at Parser.pp$3.parseExprAtom (M:\MainFiles\MyStuff\Code\react\FlexBoardToolBox\node_modules\babylon\lib\index.js:3683:12)
    at Parser.parseExprAtom (M:\MainFiles\MyStuff\Code\react\FlexBoardToolBox\node_modules\babylon\lib\index.js:7016:22)
    at Parser.pp$3.parseExprSubscripts (M:\MainFiles\MyStuff\Code\react\FlexBoardToolBox\node_modules\babylon\lib\index.js:3427:19)
    at Parser.pp$3.parseMaybeUnary (M:\MainFiles\MyStuff\Code\react\FlexBoardToolBox\node_modules\babylon\lib\index.js:3407:19)
    at Parser.pp$3.parseExprOps (M:\MainFiles\MyStuff\Code\react\FlexBoardToolBox\node_modules\babylon\lib\index.js:3337:19)
    at Parser.pp$3.parseMaybeConditional (M:\MainFiles\MyStuff\Code\react\FlexBoardToolBox\node_modules\babylon\lib\index.js:3314:19)
    at Parser.pp$3.parseMaybeAssign (M:\MainFiles\MyStuff\Code\react\FlexBoardToolBox\node_modules\babylon\lib\index.js:3277:19)
    at Parser.parseMaybeAssign (M:\MainFiles\MyStuff\Code\react\FlexBoardToolBox\node_modules\babylon\lib\index.js:6242:20)
[nodemon] app crashed - waiting for file changes before starting...

我的 package.json文件

{
  "name": "flex_board_tools",
  "version": "1.0.0",
  "description": "tool box",
  "main": "server.js",
  "scripts": {
    "start": "npm run build && babel-node src/server/server.js",
    "start:dev": "cross-env NODE_ENV=development && npm run build:dev && nodemon --exec babel-node -- src/server/server.js",
    "start:universal": "cross-env UNIVERSAL=true && npm run start",
    "start:dev:universal": "cross-env NODE_ENV=development && cross-env UNIVERSAL=true && npm run start:dev",
    "build": "cross-env NODE_ENV=production webpack -p",
    "build:dev": "webpack -d",
    "build:dev:watch": "webpack -d --watch"
  },
  "author": "Bender",
  "license": "MIT",
  "dependencies": {
    "babel-cli": "^6.18.0",
    "babel-core": "^6.18.2",
    "babel-preset-es2015": "^6.18.0",
    "babel-preset-react": "^6.16.0",
    "babel-preset-stage-2": "^6.24.1",
    "ejs": "^2.5.2",
    "express": "5.0.0-alpha.5",
    "react": "15.4.2",
    "react-addons-css-transition-group": "^15.4.0",
    "react-dom": "15.4.2",
    "react-router-dom": "^4.0.0",
    "react-toolbox": "^2.0.0-beta.8"
  },
  "devDependencies": {
    "babel-loader": "^6.4.1",
    "babel-register": "^6.18.0",
    "cross-env": "^4.0.0",
    "css-loader": "^0.28.0",
    "eslint": "^3.18.0",
    "eslint-config-airbnb": "^14.1.0",
    "eslint-plugin-import": "^2.2.0",
    "eslint-plugin-jsx-a11y": "^4.0.0",
    "eslint-plugin-react": "^6.10.3",
    "extract-text-webpack-plugin": "^2.1.0",
    "isomorphic-style-loader": "^2.0.0",
    "nodemon": "^1.11.0",
    "style-loader": "^0.16.1",
    "webpack": "2.2.1"
  }
}

我的 webpack.config.babel.js

import path from 'path';
const ExtractTextPlugin = require("extract-text-webpack-plugin");

console.log("DIR: " + __dirname);
const config = {
    entry: {
        js: './src/client/app-client.js',
    },
    output: {
        path: path.join(__dirname, 'src', 'client', 'static', 'js'),
        filename: 'bundle.js',
    },
    module: {
        rules: [
            {
                test: [/\.jsx$/, /\.js$/], //path.join(__dirname, 'src'),
                exclude: ["bower_components", "node_modules"],
                use: {
                    loader: 'babel-loader',
                    options: 'cacheDirectory=.babel_cache',
                },
            },

            {
                test: /\.css$/,
                use: [
                    { loader: 'style-loader' },
                    { loader: 'css-loader' }
                ],
                include: [
                    path.resolve(__dirname, "src","client")
                ],
            }

        ]



    },
    plugins: [

    ]
    ,

};

export default config;

示例用法(也尝试导入“./text.css”):

import React from 'react';   
import css from './text.css';


export class Test1 extends React.Component {


 render() {
    return (<div className="test">
      Test1 File

    </div>
    );
  }
}

export default Test1;

text.css

.test{ 
    background: blue;
    font-size: 1.234px; 
}

我已经好几个小时了,似乎无法找到什么问题。

5 个答案:

答案 0 :(得分:2)

尝试像这样导入你的CSS:

import "./text.css";

请分享你的CSS。

答案 1 :(得分:2)

由于您正在渲染依赖于后端webpack CSS加载器的React组件,因此在Express服务器上,您需要通过webpack运行服务器端代码,就像执行客户端代码一样。

在我目前正在进行的项目中,我有两个webpack构建,每个构建都有自己的配置。一个产生一个名为server.js的包,另一个产生client.js。在生产中,我通过运行node server.js来启动服务器。对于本地开发人员,我使用的脚本在检测到后端更改时重建server.js

看起来像这样(文件名 backend-dev.js ):

const path = require('path');
const webpack = require('webpack');
const spawn = require('child_process').spawn;

const compiler = webpack({
    // add your webpack configuration here
});
const watchConfig = {
    // compiler watch configuration
    // see https://webpack.js.org/configuration/watch/
    aggregateTimeout: 300,
    poll: 1000
};

let serverControl;

compiler.watch(watchConfig, (err, stats) => {
    if (err) {
        console.error(err.stack || err);
        if (err.details) {
            console.error(err.details);
        }
        return;
    }

    const info = stats.toJson();

    if (stats.hasErrors()) {
        info.errors.forEach(message => console.log(message));
        return;
    }

    if (stats.hasWarnings()) {
        info.warnings.forEach(message => console.log(message));
    }

    if (serverControl) {
        serverControl.kill();
    }

    // change server.js to the relative path to the bundle created by webpack, if necessary
    serverControl = spawn('node', [path.resolve(__dirname, 'server.js')]);

    serverControl.stdout.on('data', data => console.log(data.toString()));
    serverControl.stderr.on('data', data => console.error(data.toString()));
});

您可以使用

在命令行上启动此脚本
node backend-dev.js

当您对服务器代码进行更改时,webpack将重新编译并重新启动您的服务器。

请注意,我已从上面的示例中省略了实际的webpack配置,因为您的里程会有所不同。您在开头插入它,请参阅代码注释。

答案 2 :(得分:1)

如果你想使用简单的css:

import './text.css';

但是如果你想使用CSS模块,我认为根据导入中添加的css,检查https://github.com/css-modules/css-modules

另外,尝试更改webpack配置:

{
    test: /\.css$/,
    loader: 'style-loader!css-loader!',
  },

检查示例:

答案 3 :(得分:1)

我不得不从以下地址删除:

{
  test: /\.css$/,
  use: [
         { loader: 'style-loader' },
         { loader: 'css-loader' }
       ],
       include: [
                    path.resolve(__dirname, "src","client")
       ],
}

为:

 {
      test: /\.css$/,
      use: [
             { loader: 'style-loader' },
             { loader: 'css-loader' }
           ],
    }

这个适用于我的情况。我不知道为什么。

答案 4 :(得分:0)

要创建npm软件包,您可以按照以下步骤进行构建:

module: {
    rules: [
      {
        test: /\.js$/,
        include: path.resolve(__dirname, 'src'),
        exclude: /(node_modules|bower_components|build)/,
        loader: 'babel-loader'
      },
      {
        test: /\.(css|less)$/,
        use: ["style-loader", "css-loader"]
      }
    ]
  },