dob*_*ler 7 import dynamic webpack
我喜欢使用importwebpack 3 中的命令动态导入块的能力。不幸的是,它似乎只能在资源位于服务器上相当静态的目录配置中时才能使用。
在我的环境中,html 页面在后端动态生成(假设http:/localhost/app)。所有其他资源(js、css、图像等)都在不同的目录中(比如http:/localhost/res),但另外res不是静态的,而是可以在后端动态更改。
只要我不使用任何动态导入,一切都会按预期工作,但是当尝试动态加载任何块时,这会失败,因为默认情况下 webpack 期望块在其中,http:/localhost/app而我无法使用,publicPath因为资源所在的 url 是动态的。
有没有办法(运行时)配置 webpack 以加载相对于当前资源所在路径的资源。例如,如果page1.js位于 中的块http:/localhost/resA动态加载块,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>
Run Code Online (Sandbox Code Playgroud)
文件src/page1.js将可用为http:/localhost/resA/page1.bundle.js:
import(/* webpackChunkName: "sub1" */ './sub1').then(({MyClass}) => {/*...*/});
Run Code Online (Sandbox Code Playgroud)
文件src/sub1将可用为http:/localhost/resA/sub1.bundle.js:
export class MyClass {};
Run Code Online (Sandbox Code Playgroud)
文件`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;
Run Code Online (Sandbox Code Playgroud)
解决方案是__webpack_public_path__按照https://webpack.js.org/guides/public-path 中的描述使用。
| 归档时间: |
|
| 查看次数: |
9279 次 |
| 最近记录: |