反应 - 导入图像

时间:2017-11-14 16:39:39

标签: reactjs import webpack

我想拥有一个全局变量或其他东西,以便我可以在需要时轻松更改路径。当我构建它时,我也希望有一条不同的路径。

有没有更好的方法导入而不使用require?

  const URL="./../../img";

 //withURL doesn't work
    export const logo1 = require(URL+ "/Global/logo1.png");

//this works but too long
    export const logo2 = require("./../../img/Editorial/logo2.jpg");

有什么想法吗?在webpack中有没有办法可以设置它?

这是我的网站:

var webpack = require("webpack");
var path = require("path");

var ExtractTextPlugin = require("extract-text-webpack-plugin");
var HtmlWebpackPlugin = require("html-webpack-plugin");

var extractPlugin = new ExtractTextPlugin({
    filename: "App.css"
});

module.exports = {
    entry: './src/js/index.js',
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'app.bundle.js',

    },
    module: {
        rules: [
            {
                test: /\.js$/,
                use: [
                    {
                        loader: 'babel-loader',
                        options: {
                            presets: ['react', 'es2015']
                        }
                    }
                ]
            },
            {
                test: /\.css$/,
                use: ExtractTextPlugin.extract({
                    use: ['css-loader']
                })
            },
            {
                test: /\.html$/,
                use: ['html-loader']
            },
            {
                test: /\.(png|jpg|svg)$/,
                use: [
                        {
                            loader: 'file-loader',
                            options: {
                                name:'[name].[ext]',
                                outputPath: 'img/'
                            }  
                        }
                    ]
            }
        ],
    },
    plugins: [
        extractPlugin,
        new HtmlWebpackPlugin({
            template: 'src/index.html'
        })
    ]
};

1 个答案:

答案 0 :(得分:0)

这是通过带有url-loader插件的webpack完成的。

此插件允许您需要资源,如图像,并返回一个网址。

import imageUrl from './url/image.png';

console.log(imageUrl) // "/public/path/0dcbbaa7013869e351f.png"

url是资源的内容哈希,因此可以长期缓存。

但是,您还希望在运行时生成资源的路径。如果你使用的是ES6模块,那么你就不能这样做(好吧,你可以使用这种语法https://webpack.js.org/api/module-methods/#import-),但是从你的例子来看,似乎你不是因为你使用{{1} }。在这种情况下,如果您已正确配置require,则问题似乎是

url-loader

路径不会在const URL="./../../img"; export const logo1 = require(URL+ "/Global/logo1"); 或您的webpack配置中定义的某个扩展名上结束。您是否尝试添加.png