使用 Webpack - ES6 设置延迟加载组件的正确路径 [英] Set correct path to lazy-load component using Webpack - ES6
问题描述
在我的 app.js 文件中,我在使用延迟加载技术导入另一个模块(与文档中相同)的函数中有以下事件:
In my app.js file I have the following event inside a function where I import another module (same as in the docs) using the lazy-loading technique:
button.onclick = e => import(/* webpackChunkName: "print" */ './print').then(module => {
var print = module.default;
print();
});
在我的 webpack 配置中,我设置了这个(除了 Babel、SASS 加载器等):
And in my webpack config I set up this (besides Babel, SASS loaders, etc):
const path = require('path');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
module.exports = {
watch: true,
entry: {
main: ['babel-polyfill', './src/js/app.js','./src/sass/main.sass']
},
output: {
chunkFilename: '[name].bundle.js',
path: path.resolve(__dirname, "dist"),
filename: '[name].js',
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ["babel-preset-env", "babel-preset-stage-0"]
}
}
},
{
test: /\.sass$/,
exclude: /node_modules/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
'css-loader',
{
loader: 'sass-loader',
query: {
sourceMap: false,
},
},
],
}),
},
]
}
}
问题是路径./print"来自我的src"文件夹,而不是来自我的dist"文件夹,webpack 将所有包放在那里,所以我收到 404 错误.如果我将路径更改为./dist/print",那么 webpack 构建将崩溃.
The problem is the path "./print" is from my "src" folder and not from my "dist" folder, where webpack puts all the bundles, so I get a 404 error. If I change the path to "./dist/print" then the webpack build will crash.
我是否缺少 webpack 配置?
Am I missing a webpack configuration?
文件夹结构:
src
js
app.js
print.js
dist
main.bundle.js
print.bundle.js
推荐答案
你不必用 dist 文件夹中的模块路径处理,只需在 src 文件夹中.
You don't have to treat with the modules path in dist folder, only in src folder.
我认为有两种解决方案:
There is two solutions I think :
1/在导入语句中指定 src 路径:
1/ Specify src path in your import statement :
button.onclick = e => import(/* webpackChunkName: "print" */ './src/js/print').then(module => {
var print = module.default;
print();
});
2/就我个人而言,我通常做的是将 src 文件夹添加到配置文件中的解析路径:
2/ Personally, What I usually do is to add src folder to resolved paths in config file:
resolve: {
modules: [
path.resolve('./node_modules'),
path.resolve('./src/js')
],
extensions: ['.json', '.js']
},
然后您的代码应该可以在不更改行的情况下工作.
Your code should then work without changing a line.
这篇关于使用 Webpack - ES6 设置延迟加载组件的正确路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!