【问题标题】:Unable to use webpack dynamic import because of static publicPath由于静态 publicPath 无法使用 webpack 动态导入
【发布时间】:2018-05-17 05:48:43
【问题描述】:

我喜欢在 webpack 3 中使用 import 命令动态导入块的能力。不幸的是,它似乎只能在资源位于服务器上相当静态的目录配置中时使用。

在我的环境中,html 页面在后端动态生成(比如说http:/localhost/app)。所有其他资源(js、css、图像等)都在不同的目录中(比如说http:/localhost/res),但另外res 不是静态的,而是可以在后端动态变化。

只要我不使用任何动态导入,一切都会按预期工作,但是当尝试动态加载任何块时,这会失败,因为 webpack 默认情况下希望这些块位于 http:/localhost/app 中,而我不能使用 publicPath,因为 url资源所在的位置是动态的。

有没有办法(运行时)配置 webpack 加载相对于当前资源所在路径的资源。 例如,如果位于http:/localhost/resA 中的块page1.js 动态加载块sub1.js,他应该在http:/localhost/resA 而不是http:/localhost/app 中查找它。

生成的 html 将在 http:/localhost/app/page1:

上提供
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
    </head>
    <body>
        <script src="http:/localhost/resA/page1.bundle.js"></script>
    </body>
</html>

文件 src/page1.js 将作为 http:/localhost/resA/page1.bundle.js 提供:

import(/* webpackChunkName: "sub1" */ './sub1').then(({MyClass}) => {/*...*/});

文件 src/sub1 将作为 http:/localhost/resA/sub1.bundle.js 提供:

export class MyClass {};

文件`webpack.config.js':

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

function config(env) {
    return {
        entry: {
            index: ['./src/page1.js']
        },
        output: {
            filename: '[name].bundle.js',
            chunkFilename: '[name].bundle.js',
            path: path.resolve(__dirname, 'dist'),
            publicPath: './'
        },
        module: {
            rules: [
                {
                    test: /\.js$/i,
                    include: /src/,
                    exclude: /node_modules/,
                    use: {
                        loader: 'babel-loader'
                    }
                }
            ]
        },
        devtool: 'source-map'
    };
}

module.exports = config;

【问题讨论】:

    标签: dynamic webpack import


    【解决方案1】:

    解决方案是使用__webpack_public_path__,如https://webpack.js.org/guides/public-path 中所述。

    【讨论】:

    • 为什么对公共文档的简短引用可以解决您的问题?您的问题陈述非常详细,而解决方案却不是。
    • 是否可以在运行时覆盖css中指定资产的公共路径?如果不是,一般怎么做?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-31
    • 1970-01-01
    相关资源
    最近更新 更多