由于静态 publicPath 的原因,无法使用 webpack 动态导入功能。

9
我很欣赏在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;
1个回答

8

6
为什么对公共文档的简短引用可以解决你的问题?你的问题陈述非常详细,但解决方案却不是。 - mliebelt
1
在运行时覆盖CSS中指定的资源公共路径是否可能?如果不行,一般该如何处理? - Varun Hegde

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接