【问题标题】:How to handle static assets with webpack server side?如何使用 webpack 服务器端处理静态资产?
【发布时间】:2017-02-15 18:20:30
【问题描述】:

我正在尝试创建一个通用的 react 应用程序(在服务器和客户端上都使用 webpack)并在图像导入方面遇到困难。我想写这个:

import someImage from './someImage.png'

const SomeImage = () => <img src={someImage}/>

这是我的 webpack 配置文件:

var path              = require('path');
var webpack           = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
  entry:  [
    'webpack-dev-server/client?http://127.0.0.1:8080/',
    'webpack/hot/only-dev-server',
    './client',
    'babel-polyfill'
  ],
  output: {
    path:     path.join(__dirname, 'dist'),
    filename: 'bundle.js'
  },
  resolve: {
    modulesDirectories: ['node_modules', 'shared'],
    extensions:         ['', '.js', '.jsx']
  },
  module: {
    loaders: [
      {
        test:    /\.jsx?$/,
        exclude: /node_modules/,
        loaders: ['babel']
      },
      {
        test: /\.css/,
        exclude: /node_modules/,
        loader: ExtractTextPlugin.extract('style', 'css?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]')
      },
      {
        test: /\.(jpe?g|png|gif|svg)$/i,
        loaders: [
          'file?emitFile=false',
        ]
      }
    ]
  },
  plugins: [
    new ExtractTextPlugin('styles.css', { allChunks: true }),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin()
  ],
  devtool: 'inline-source-map',
  devServer: {
    hot: true,
    proxy: {
      '*': 'http://127.0.0.1:' + (process.env.PORT || 3000)
    },
    host: '127.0.0.1'
  }
};

显然它在服务器端不起作用,因为node 尝试读取./someImage.png 文件的内容,导致错误。

我该如何处理?我知道有诸如webpack-isomorphic-toolsuniversal-webpack 之类的包,甚至可以发出或不发出文件的文件加载器包,但我不明白在我的通用应用程序中使用它。

【问题讨论】:

  • 你为什么要导入/内联图像开始?如果我是你,为了你的理智,请远离。
  • 因为在我的组件中导入资产非常方便。这使整个事物都封装起来并且更加模块化。但也许有更好的选择?
  • @Pcriulan 您找到解决问题的方法了吗?如果有,请分享!
  • 嗨,@Pcriulan,你找到解决方案了吗,我也遇到了同样的问题。我也尝试使用文件加载器,但它不起作用。同样使用 webpack-isomorphic-tools,它给了我“未找到资产”错误。

标签: javascript node.js image webpack server-side-rendering


【解决方案1】:

我正在使用带有 emitFile: false 的文件加载器来从服务器端的捆绑中排除资产。按预期工作。

    module: {
      rules: [
        {
          test: /\.(png|jpeg|gif|ico|ttf|css)$/,
          use: [
            {
              loader: "file-loader",
              options: { emitFile: false },
            },
          ],
        }
      ],
    },

【讨论】:

    猜你喜欢
    • 2020-08-07
    • 1970-01-01
    • 2019-09-21
    • 1970-01-01
    • 2011-03-29
    • 1970-01-01
    • 2016-04-24
    • 1970-01-01
    • 2011-07-13
    相关资源
    最近更新 更多