Next.js 中如何使用 Webpack 4 及以上版本
随着 Webpack 4 的发布,它被认为是更快、更简单和更强大的打包工具。Next.js 作为一个基于 React 的服务器渲染框架,也在其最新版本中加入了对 Webpack 4 及以上版本的支持。本文将详细介绍 Next.js 如何使用 Webpack 4 及以上版本,并提供示例代码供读者参考和学习。
一、配置 Webpack 4
Next.js 5.0 以上的版本已经默认集成了 Webpack 4,因此不需要单独安装 Webpack。但我们仍然需要配置 Webpack,以满足自己的需要。
首先,在项目根目录下创建一个名为 next.config.js 的文件,用于配置 Webpack:
// www.javascriptcn.com code example
// next.config.js
const path = require('path');
module.exports = {
webpack: (config, options) => {
config.module.rules.push({
test: /\.(png|jpe?g|gif)$/i,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
publicPath: `/_next/static/images/`,
outputPath: `${options.isServer ? '../' : ''}static/images/`,
},
},
],
});
return config;
},
};在上面的配置中,我们添加了一条规则,用于加载图片。我们将图片放到了 /_next/static/images/ 这个目录里,并在输出目录下对应的位置生成了文件。
二、自定义 Webpack 配置
如果你需要自定义 Webpack 配置,你可以将 next.config.js 修改成以下内容:
// www.javascriptcn.com code example
// next.config.js
const webpack = require('webpack');
const path = require('path');
module.exports = {
webpack: (config, { dev }) => {
config.plugins.push(new webpack.IgnorePlugin(/\/__tests__\//));
if (dev) {
console.log('Webpack dev build');
} else {
console.log('Webpack prod build');
}
return config;
},
};这里,我们添加了一个忽略测试代码的插件,并在控制台输出当前运行环境是开发环境还是生产环境。
三、使用 CSS
Next.js 内置了处理 CSS 的能力,可以直接将 CSS 文件导入到页面中。但是如果你使用了其他预处理器,例如 LESS、SASS 或 SCSS,你需要在项目中安装对应的 loader。
我们需要在 devDependencies 中引入 @zeit/next-less 和 less:
npm install --save-dev @zeit/next-less less
在 next.config.js 中配置 withLess:
// next.config.js
const withLess = require('@zeit/next-less');
module.exports = withLess({
lessLoaderOptions: {
javascriptEnabled: true,
},
});在项目中,你可以使用 import 导入 LESS 文件:
import '../styles/main.less';
四、使用 TypeScript
Next.js 同样支持使用 TypeScript 进行开发,但需要在项目中安装 @zeit/next-typescript 和 typescript:
npm install --save-dev @zeit/next-typescript typescript
在 next.config.js 中配置 withTypescript:
// next.config.js
const withTypescript = require('@zeit/next-typescript');
module.exports = withTypescript();现在你可以在项目中使用 TypeScript :
// www.javascriptcn.com code example
// pages/index.tsx
import React from 'react';
interface Props {
message: string;
}
const IndexPage: React.FC<Props> = ({ message }) => {
return (
<div>Hello {message}</div>
);
}
IndexPage.getInitialProps = async ({ req }) => {
const message = 'World';
return { message };
};
export default IndexPage;以上是使用 Webpack 4 及以上版本的 Next.js 配置方法,现在您可以在项目中更快、更优秀的使用 Webpack 4 来打包您的代码了。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/67d6a69ea941bf7134c6d49d