我有一个用ES6编写的组件的React应用程序-通过Babel和Webpack进行了编译。
在某些地方,我想包含特定CSS文件和特定组件,如react webpack手册中所建议
但是,如果在任何组件文件中,我都需要静态CSS资产,例如:
import '../assets/css/style.css';
然后编译失败并显示错误:
SyntaxError: <PROJECT>/assets/css/style.css: Unexpected character '#' (3:0)
at Parser.pp.raise (<PROJECT>\node_modules\babel-core\lib\acorn\src\location.js:73:13)
at Parser.pp.getTokenFromCode (<PROJECT>\node_modules\babel-core\lib\acorn\src\tokenize.js:423:8)
at Parser.pp.readToken (<PROJECT>\node_modules\babel-core\lib\acorn\src\tokenize.js:106:15)
at Parser.<anonymous> (<PROJECT>\node_modules\babel-core\node_modules\acorn-jsx\inject.js:650:22)
at Parser.readToken (<PROJECT>\node_modules\babel-core\lib\acorn\plugins\flow.js:694:22)
at Parser.pp.nextToken (<PROJECT>\node_modules\babel-core\lib\acorn\src\tokenize.js:98:71)
at Object.parse (<PROJECT>\node_modules\babel-core\lib\acorn\src\index.js:105:5)
at exports.default (<PROJECT>\node_modules\babel-core\lib\babel\helpers\parse.js:47:19)
at File.parse (<PROJECT>\node_modules\babel-core\lib\babel\transformation\file\index.js:529:46)
at File.addCode (<PROJECT>\node_modules\babel-core\lib\babel\transformation\file\index.js:611:24)
看来,如果我尝试在Component文件中要求CSS文件,那么Babel加载程序会将其解释为另一个来源,并尝试将CSS转换为Javascript。
这是预期的吗?有没有一种方法可以实现-允许已转译的文件显式引用不需转译的静态资产?
我为.js / jsx和CSS资产都指定了加载程序,如下所示:
module: {
loaders: [
{ test: /\.css$/, loader: "style-loader!css-loader" },
{ test: /\.(js|jsx)$/, exclude: /node_modules/, loader: 'babel'}
]
}
详细信息如下:
webpack.common.js - A base webpack config I use, so I can share properties between dev and production.
Gruntfile.js - Gruntfile used for development. As you can see it requires the webpack config above and adds some development properties to it. Could this be causing the problem?
Html.jsx - My HTML jsx component that tries to import/require the CSS. This is an isomorphic app (using Fluxbile), hence needing to have the actual HTML as a rendered component. Using the require statement seen in this file, in any part of my application, gives the error described.
It seems to be something to do with grunt. If I just compile with webpack --config webpack.common.js
then I get no errors.
Short answer: It's a node runtime error. Trying to load CSS on the server in isomorphic apps is not a good idea.
当我要执行服务器端渲染时,我也遇到了同样的问题。
所以我写了一个postcss插件postcss-hash-classname。
您不需要直接使用CSS。
您需要CSS类名js文件。
由于您只需要js文件,因此您可以照常进行服务器端渲染。
此外,此插件还使用您的类名和文件路径生成唯一的哈希值,以解决css范围问题。
你可以尝试一下!