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

Posted

技术标签:

【中文标题】尝试使用 webpack 和 babel 加载 css 时出现意外令牌【英文标题】:Unexpected token when trying to load css with webpack and babel 【发布时间】:2017-09-19 10:47:11 【问题描述】:

我正在使用 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;

示例用法(也尝试过 import "./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; 

我已经做了好几个小时了,似乎找不到问题所在。

【问题讨论】:

您是否尝试在后端渲染 React 组件? AFAICS,您仅将 webpack 用于客户端代码,不是吗?如果你想在后端渲染 React,你也必须使用 webpack 作为后端代码 @PatrickHund 谢谢你,我将如何使用 webpack 作为我的后端代码? @Mike,你解决问题了吗?我的情况非常相似 【参考方案1】:

尝试像这样导入你的 css:

import "./text.css";

也请分享你的 CSS。

【讨论】:

我添加了css文件,也尝试使用建议的导入语法但没有成功。【参考方案2】:

由于您在 Express 服务器上渲染依赖于后端 webpack CSS 加载器的 React 组件,因此您需要通过 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 配置,因为您的里程会有所不同。在开头插入,见代码注释。

【讨论】:

【参考方案3】:

如果你想使用简单的 css:

import './text.css';

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

另外,尝试更改 webpack 配置:


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

检查示例:

使用 CSS:https://github.com/Aksana-Tsishchanka/react-routing/blob/master/src/components/Logout.jsx

webpack.config.js:https://github.com/Aksana-Tsishchanka/react-routing/blob/master/webpack.config.js

【讨论】:

我只是想导入纯 css,我试过这个,但它不起作用。 我很确定,它必须工作。查看我的 GitHub 中的示例。我使用 Express-session 和 Json-server 作为后端。另外,为什么你将 webpack 配置命名为 webpack.config.babel.js?它必须是 webpack.config.js【参考方案4】:

我必须删除:


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

到:

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

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

【讨论】:

【参考方案5】:

要创建 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"]
      
    ]
  ,

【讨论】:

以上是关于尝试使用 webpack 和 babel 加载 css 时出现意外令牌的主要内容,如果未能解决你的问题,请参考以下文章

Webpack - Babel - 解析 JSX: SyntaxError: Unexpected token

Babel 与 webpack 加载器

Babel Webpack 错误:您可能需要适当的加载器来处理此文件类型

如何在 ES6+ 的 webpack 中的 node_modules 上使用 babel 加载器?

Webpack 热模块替换不适用于 babel-loader 和预设 es2015

无法使用Webpack 4和Babel 7导出默认值