使用Webpack解决从node_modules到Dist文件夹的相对路径

时间:2019-05-29 21:24:29

标签: reactjs webpack webpack-dev-server sass-loader

我正在使用React组件作为NPM软件包。在组件中,我有SCSS文件 使用url(../ iamges / img ..)路径,但实际上是位于Dist文件夹中的images文件夹,我如何指向Webpack从node_modules获取相对路径并从位于Dist的images文件夹中提供它? / p>

located in node_modules =>
background: url('../images/some-icon.svg') no-repeat center center; 

Webpack配置:


const webpack = require('webpack');
const path = require('path');

module.exports = {
    entry: './src/index.js',
    devtool: 'inline-module-source-map',
    output: {
        path: path.resolve(__dirname, '/dist'),
        filename: 'bundle.js',
        publicPath: '/',
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                use: {
                    loader: 'babel-loader',
                },
            },
            {
                test: /\.scss$/,
                use: [
                    { loader: 'style-loader' },
                    { loader: 'css-loader' },
                    {
                        loader: 'resolve-url-loader',
                        // options: {
                        //  debug: true,
                        //  root: path.join(__dirname, './dist/images'),
                        //  includeRoot: true,
                        //  absolute: true,
                        // },
                    },
                    {
                        loader: 'sass-loader',
                        options: {
                            sourceMap: true,
                            sourceMapContents: false,
                        },
                    },
                ],
            },
            {
                test: /\.css$/,
                loaders: ['style-loader', 'css-loader'],
            },
            {
                test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
                use: {
                    loader: 'url-loader?name=/images/[name].[ext]',
                    options: {
                        limit: 10000,
                    },
                },
            },
        ],
    },
    resolve: {
        extensions: ['.js', '.jsx'],
        // modules: [path.resolve(__dirname, '/images'), 'node_modules'],
        alias: {
            'react-redux': path.resolve('./node_modules/react-redux'),
        },
    },
    plugins: [new webpack.HotModuleReplacementPlugin()],
    devServer: {
        hot: true,
        publicPath: '/dist/',
    },
};

babel.config.js

module.exports = {
    // presets: ['@babel/preset-env', '@babel/preset-react'],
    plugins: [
        '@babel/plugin-proposal-class-properties',
        '@babel/plugin-proposal-export-default-from',
        '@babel/transform-runtime',
    ],
    sourceType: 'unambiguous',
    presets: [
        [
            '@babel/preset-env',
            {
                targets: {
                    node: 'current',
                },
            },
        ],
        '@babel/preset-react',
    ],
};


dist
   -- images
   -- index.html

错误:

ERROR in ./node_modules/comp/src/styles/details.scss (./node_modules/css-loader!./node_modules/resolve-url-loader!./node_modules/sass-loader/lib/loader.js??ref--5-3!./node_modules/compdetails/src/styles/details.scss)
Module not found: Error: Can't resolve '../images/icon.svg'

1 个答案:

答案 0 :(得分:2)

在CSS中通过url('...')引用的任何内容都将参考已部署的应用程序的路径进行计算(除非不使用变量或函数,否则CSS不会计算路径):

例如: 如果您引用的组件SCSS模块具有background: url('../images/some-icon.svg') no-repeat center center;

最终的CSS编译将是相同的(这也是因为该组件未使用任何SCSS变量或函数来计算最终路径)。

因此您的应用程序将始终尝试以以下方式查找该图像:

示例:http://localhost:3000/../images/some-icon.svg,这是一个问题。 (..被称为父目录)

如果您尝试使用某些带有http://localhost:3000/sub-url/的子URL(也称为子上下文)运行应用程序,并且将图像与sub-url文件夹平行,它将自动运行。

-- /
   |
   |-- sub-url
         |
         |-- index.html
   |-- images
         |
         |-- some-icon.svg

另一个选项可以用您的组件覆盖SCSS组件。

您已经找到了使用resolve-url-loader的解决方案,但是在这种情况下,您需要将组件的scss文件导入到scss中。

因此您的 webpack配置应如下所示:

const webpack = require('webpack');
const path = require('path');

module.exports = {
    entry: './src/index.js',
    devtool: 'inline-module-source-map',
    output: {
        path: path.resolve(__dirname, '/dist'),
        filename: 'bundle.js',
        publicPath: '/',
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                use: {
                    loader: 'babel-loader',
                },
            },
            {
                test: /\.scss$/,
                use: [
                    { loader: 'style-loader' },
                    { loader: 'css-loader' },
                    // CHANGE HERE
                    {
                        loader: 'resolve-url-loader',
                        options: {
                          root: '/images', // considering all your images are placed in specified folder. Note: this is just a string that will get as prefix to image path
                          includeRoot: true,
                          absolute: true,
                        },
                    },
                    {
                        loader: 'sass-loader',
                        options: {
                            sourceMap: true,
                            sourceMapContents: false,
                        },
                    },

                ],
            },
            {
                test: /\.css$/,
                loaders: ['style-loader', 'css-loader'],
            },
            {
                test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
                use: {
                    loader: 'url-loader?name=/images/[name].[ext]',
                    options: {
                        limit: 10000,
                    },
                },
            },
        ],
    },
    resolve: {
        extensions: ['.js', '.jsx'],
        // modules: [path.resolve(__dirname, '/images'), 'node_modules'],
        alias: {
            'react-redux': path.resolve('./node_modules/react-redux'),
        },
    },
    plugins: [new webpack.HotModuleReplacementPlugin()],
    devServer: {
        hot: true,
        publicPath: '/dist/',
    },
};

我希望这会有所帮助。