我正在尝试将我的应用迁移到Webpack4。我的头已经疼了。
动态导入-这是我的代码拆分方法(逐页)。但是我无法正常工作。使用以下软件包设置了非常简单的测试器:
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^7.1.4",
"babel-plugin-transform-async-to-generator": "^6.24.1",
"babel-polyfill": "^6.26.0",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"css-loader": "^0.28.11",
"html-loader": "^0.5.5",
"html-webpack-plugin": "^3.2.0",
"mini-css-extract-plugin": "^0.4.0",
"react": "^16.4.1",
"react-dom": "^16.4.1",
"webpack": "^4.12.0",
"webpack-cli": "^3.0.8",
"webpack-dev-server": "^3.1.4"
}
这是我的主要测试应用程序:
import React from "react";
import ReactDOM from "react-dom";
import style from "./main.css";
import pageLoader from './pageLoader';
class App extends React.Component {
render() {
let page = pageLoader();
return (
<div>
<p>React here!</p>
{page}
</div>
);
}
};
export default App;
ReactDOM.render(<App />, document.getElementById("app"));
我想用单独的包动态加载页面。
import React from "react";
import ReactDOM from "react-dom";
import style from "./main.css";
const Page1 = () => {
return (
<div>
<p>Page1 here!</p>
</div>
);
};
export default Page1;
到目前为止,这是我的webpack.config:
const path = require('path');
const HtmlWebPackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
entry: {
polyfill: 'babel-polyfill',
app: './src/index.js'
},
output: {
filename: '[name].bundle.js',
chunkFilename: '[name].bundle.js', //name of non-entry chunk files
path: path.resolve(__dirname, 'dist')
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.html$/,
use: [
{
loader: "html-loader",
options: { minimize: true }
}
]
},
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, "css-loader"]
},
]
},
plugins: [
new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "./index.html"
}),
new MiniCssExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css"
})
]
};
现在这是构建错误的部分。这是调用动态导入的函数:
function pageLoader() {
return import(/* webpackChunkName: "page1" */ './Page1')
.then(page => {
return page.default;
});
}
export default pageLoader;
我在构建时遇到此错误:
ERROR in ./src/test/pageLoader.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: Unexpected token (2:8)
1 | function pageLoader() {
> 2 | return import(/* webpackChunkName: "page1" */ './Page1')
| ^
3 | .then(page => {
4 | return page;
5 | });
我读过的所有内容都说这是进行设置的方法。我在做什么错了?
答案 0 :(得分:1)
我遇到的问题是修复程序:
npm install --save-dev @babel/plugin-syntax-dynamic-import
将以下行添加到 .babelrc
"plugins": ["@babel/plugin-syntax-dynamic-import"],
来源:
https://webpack.js.org/guides/code-splitting/#dynamic-imports
https://babeljs.io/docs/plugins/syntax-dynamic-import/#installation
希望这对以后的人有帮助。
答案 1 :(得分:0)
只是为那些沿着这条路走的人做一个更新:如果你使用 React,我会推荐 react-loadable,这使得基于每个组件的动态导入变得非常容易......很多大公司使用它。