Importing CSS files in Isomorphic React Components

前端 未结 10 1278
失恋的感觉
失恋的感觉 2020-11-30 22:01

I have a React application with Components written in ES6 - transpiled via Babel and Webpack.

In some places I would like to include specific CSS files with specific

相关标签:
10条回答
  • 2020-11-30 22:39

    You probably have an error in your Webpack config where you're using the babel-loader for all files, and not just .js files. You want to use a css loader for .css files.

    But you shouldn't use import for loading any other module than Javascript modules, because once imports are implemented in browsers, you will only be able to import Javascript files. Use require instead in cases where you need Webpack specific functionality.

    ORIGINAL POST

    Webpack uses require and Babel lets you use import from ES6 which mostly do the same thing (and Babel transpiles the import to a require statement), but they are not interchangable. Webpacks require function lets you specify more than just a module name, it lets you specify loaders as well, which you cannot do with ES6 imports. So if you want to load a CSS file, you should use require instead of import.

    The reason is that Babel is just a transpiler for what's coming in ES6, and ES6 will not allow you to import CSS files. So Babel won't allow you to do that either.

    0 讨论(0)
  • 2020-11-30 22:39

    I also met the same problem when I want to do the server-side render.

    So I write a postcss plugin, postcss-hash-classname.

    You don't require css directly.

    You require your css classname js file.

    Because all you require is js file, you can do the server-side render as usual.

    Besides, this plugin also use your classname and file path to generate unique hash to solve css scope problem.

    You can try it!

    0 讨论(0)
  • 2020-11-30 22:42

    We had a similar problem with our isomorphic app (and a lot of other problems, you can find details here). As for the problem with CSS import, at first, we were using process.env.BROWSER. Later we've switched to babel-plugin-transform-require-ignore. It works perfectly with babel6.

    All you need is to have the following section in your .babelrc

    "env": {
       "node": {
         "plugins": [
           [
             "babel-plugin-transform-require-ignore", { "extensions": [".less", ".css"] }
           ]
         ]
       }
    }
    

    After that run your app with BABEL_ENV='node'. Like that:

    BABEL_ENV='node' node app.js.
    

    Here is an example of how a production config can look like.

    0 讨论(0)
  • 2020-11-30 22:45

    You can also try this https://github.com/halt-hammerzeit/webpack-isomorphic-tools

    or this https://github.com/halt-hammerzeit/webpack-react-redux-isomorphic-render-example

    0 讨论(0)
提交回复
热议问题