【发布时间】: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;
【问题讨论】: