如何在同构React上导入CSS文件-Webpack [英] How to import CSS file on Isomorphic React - Webpack

查看:99
本文介绍了如何在同构React上导入CSS文件-Webpack的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用express,react和webpack创建一个同构的react应用.

I'm trying to create an isomorphic react app using express, react, and webpack.

一切正常,直到我在一个组件中导入一个css文件.我知道node无法处理此导入,但是有人可以解释github上的此包如何允许其组件具有css导入行吗?

Everything works fine until I import a css file in one of my components. I understand node can not handle this import, but can someone explain how this package on github allows their components to have a css import line?

https://github.com/kriasoft/react-starter-kit

我想使我的项目与此类似.他们是否在任何地方都有一行,在渲染组件时服务器会忽略该行?

I would like to make my project similar to that. Do they have a line anywhere that has the server ignore that line when rendering components?

这是我得到的错误

SyntaxError: /home/USER/Code/shared/general/ru/src/components/MainPage/MainPage.scss: Unexpected token (1:1)
> 1 | @import '../variables.scss';
    |  ^
  2 | 
  3 | .MainPage {
  4 |   background-color: $primary-color;
    at Parser.pp.raise (/home/USER/Code/shared/general/ru/node_modules/babylon/lib/parser/location.js:24:13)
    at Parser.pp.unexpected (/home/USER/Code/shared/general/ru/node_modules/babylon/lib/parser/util.js:82:8)
    at Parser.pp.parseExprAtom (/home/USER/Code/shared/general/ru/node_modules/babylon/lib/parser/expression.js:425:12)
    at Parser.parseExprAtom (/home/USER/Code/shared/general/ru/node_modules/babylon/lib/plugins/jsx/index.js:412:22)
    at Parser.pp.parseExprSubscripts (/home/USER/Code/shared/general/ru/node_modules/babylon/lib/parser/expression.js:236:19)
    at Parser.pp.parseMaybeUnary (/home/USER/Code/shared/general/ru/node_modules/babylon/lib/parser/expression.js:217:19)

推荐答案

您还需要另一个加载器才能使CSS/样式加载器正常工作.

You need yet another loader to make css/style loaders to work.

https://www.npmjs.com/package/webpack-isomorphic-tools

但是Webpack仅用于客户端代码开发:它在代码内找到所有require()调用,并用各种魔术代替它们以使事情正常进行.如果您尝试在Webpack外部运行相同的源代码(例如,在Node.js服务器上),则会收到大量带有意外令牌的SyntaxErrors.这是因为在Node.js服务器上没有发生Webpack require()魔术,它只是尝试对所有资产"(样式,图像,字体,OpenGL着色器等)进行require(),就好像它们是正确的javascript编码模块一样.因此出现错误消息.

But Webpack is made for client side code development only: it finds all require() calls inside your code and replaces them with various kinds of magic to make the things work. If you try to run the same source code outside of Webpack - for example, on a Node.js server - you'll get a ton of SyntaxErrors with Unexpected tokens. That's because on a Node.js server there's no Webpack require() magic happening and it simply tries to require() all the "assets" (styles, images, fonts, OpenGL shaders, etc) as if they were proper javascript-coded modules hence the error message.

祝你好运!

我想您也想看这个SO问题. 在同构React组件中导入CSS文件

I think you also want to see this SO question. Importing CSS files in Isomorphic React Components

这篇关于如何在同构React上导入CSS文件-Webpack的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆