在本文中,您将学到babel,webpack,next.js, 飞冰的一些基础使用。
以及最重要的一点,不屈不挠的爬坑精神。
正文开始
第一步 使用飞冰的模版创建一个项目
这里选择自定义模版,只需要它生成项目框架。
注意:这里先不要添加依赖,飞冰自己安装的webpack版本会导致next.js无法使用自身的配置启动项目。

当然,你也可以像我一样尝试,找一个酷炫的模版
然后经历如下步骤
-
配置babel插件
-
配置webpack的loader
-
修改第三方UI框架代码中的document,window
-
怒删项目

第二步 添加next相关依赖和配置
添加依赖
npm install --save next react react-dom
安装完后,可以安装所有依赖了
npm install
安装完后,配置package.json文件,这里指定pages文件夹位于src下
"scripts": {
"dev": "next src"
},
到这里是不是已经迫不及待想要
npm run dev

一切看起来风和日丽,格外美丽,我们尝试显示NotFound页面
http://localhost:3000/NotFound
WTF?剧情不是这样的啊!为什么会报错,生活终于对我这只小猫咪下手了吗?

这里需要添加flie-loader来解析图片,以及sass的插件来解析scss
npm install file-loader @zeit/next-sass node-sass --save -D
然后在项目根目录新增next.js的配置文件 next.config.js
// next.config.js
const withSass = require('@zeit/next-sass');
// next.config.js is not transformed by Babel. So you can only use javascript features supported by your version of Node.js.
module.exports = withSass({
webpack: (config, { buildId, dev, isServer, defaultLoaders }) => {
// Perform customizations to webpack config
// Important: return the modified config
config.module.rules.push({
test: /\.(png|jpg|gif)$/,
use: [
{
loader: 'file-loader',
options: {},
},
],
});
return config;
},
webpackDevMiddleware: config => {
// Perform customizations to webpack dev middleware config
// Important: return the modified config
return config;
}
});
接下来继续
http://localhost:3000/NotFound
你会碰到几个 document window is undefined的错误,直接找到相应的地方增加判断
if (typeof window == 'undefined')
// or
if (typeof document == 'undefined')
然后回到BasicNotFound.jsx中,注释飞冰使用的Link,改为a标签的href
import React, { Component } from 'react';
// import { Link } from 'react-router-dom';
import IceContainer from '@icedesign/container';
import './BasicNotFound.scss';
export default class BasicNotFound extends Component {
static displayName = 'BasicNotFound';
render() {
return (
抱歉,你访问的页面不存在
您要找的页面没有找到,请返回首页继续浏览
);
}
}
const styles = {
exceptionContent: {
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
},
title: {
color: '#333',
},
description: {
color: '#666',
},
};
至此,只差最后一个坑我们就能将页面展示出来了,我们需要让项目正确的识别
import IceContainer from '@icedesign/container';
我们使用babel-plugin-module-resolver插件解决
npm install --save-dev babel-plugin-module-resolver
增加.babelrc配置文件来使用该插件
{
"presets": [
["next/babel"]
],
"plugins": [
["module-resolver", {
"root": ["./src"],
"alias": {
"@icedesign": "./node_modules/@icedesign"
}
}]
]
}
至此,页面可以正确展示。

为什么明明成功展示了,却有种失败的感觉呢。
网友评论