在不同的文件夹中加载CSS

时间:2017-03-16 13:11:39

标签: javascript css reactjs

我正在开展一个反应项目,这是我的文件夹结构:我想加载位于example.css

内的不同文件夹中的index.js
templates
  --src
    --index.js
    --index.html

static
  --css
      --example.css
  --images
  --etc

webpack.config.js

var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');

config = {
  context: __dirname,
  devtool: debug ? "inline-sourcemap" : null,
  entry: "./src/index.js",
  output: {
    path: "../../static/webpack_build",
    filename: "bundle.js"
  },
  plugins: [
    new webpack.DefinePlugin({ // <-- key to reducing React's size
      'process.env': {
        'NODE_ENV': JSON.stringify('production')
      }
    }),
    new webpack.optimize.UglifyJsPlugin(), //minify everything
    new webpack.optimize.AggressiveMergingPlugin()//Merge chunks
  ],
  module: {
         loaders: [{
                 test: /\.js$/,
                 exclude: /node_modules/,
                 loader: 'babel-loader',
                 query:
                      {
                        presets:['es2015', 'react']
                      }
             },
             {
                 test: /\.css$/,
                 loader: 'style-loader!css-loader'
             }
             ]
         },
  };

module.exports = config;

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import styles from '../../static/css/affman.css'


ReactDOM.render(
    <h1>Offer wall new version coming soon!</h1>,
  document.getElementById('root')
);

当我尝试使用webpack捆绑它时,它会发现模块未找到错误。

ERROR in ./src/index.js
Module not found: Error: Can't resolve '../../static/css/affman.css' in '/home/kishan/mobifly/mobifly_mediation_engine/templates/frontend_mobifly/src'
 @ ./src/index.js 11:14-50

1 个答案:

答案 0 :(得分:1)

尝试使用此链接指向样式:

import styles from '../css/affman.css'
enter code here

我认为问题与webpack中的输出文件夹 webpack_build 有关。也许我们应该从这个文件夹中设置链接到css

  output: {
    path: "../../static/webpack_build",
    filename: "bundle.js"
  }

我希望它会有所帮助