tailwind css_如何使用Tailwind CSS设置Next.js

tailwind css

If you’re starting a new React project, you might want to consider Next.js and Tailwind CSS. In this article, we will explain why this would be a great choice and walk you through the process of setting up a new project using these technologies.

如果您要开始一个新的React项目,则可能需要考虑Next.js和Tailwind CSS 。 在本文中,我们将解释为什么这将是一个不错的选择,并引导您完成使用这些技术建立新项目的过程。

为什么选择Next.js? (Why Next.js?)

There are many important details you need to consider when you start a new project with React. Your code has to be bundled using a bundler like webpack and transformed using a compiler like Babel. Create React App can be a nice tool to handle this for you and give you a massive head start, but what about code-splitting, pre-rendering for performance, and SEO or server-side rendering?

在使用React启动新项目时,需要考虑许多重要的细节。 您的代码必须使用诸如webpack的捆绑器进行捆绑,并使用诸如Babel的编译器进行转换。 创建React App可能是一个很好的工具,可以为您处理此问题并为您提供大量的开端,但是代码拆分,性能的预渲染以及SEO或服务器端渲染又如何呢?

To build a complete React application, you need more than CRA provides you. You can save yourself some time by using Next.js, a React framework that provides a solution to all of these problems above. If you want to read more about CRA vs. Next.js, check out Stack choices: Create React App vs Next.js.

要构建一个完整的React应用程序,您需要的不仅仅是CRA提供的。 您可以使用Next.js(一个React框架,为上述所有问题提供解决方案)节省一些时间。 如果您想了解有关CRA与Next.js的更多信息,请查看堆栈选择:Create React App vs Next.js。

为什么要使用Tailwind CSS? (Why Tailwind CSS?)

Tailwind CSS is a CSS framework, but it’s different than most other frameworks like Bootstrap, Material, or Ant Design. It’s a utility-first framework, which means it doesn’t focus on predesigned components like buttons, cards, and alerts. It provides low-level utility classes that let you build completely custom designs without leaving your HTML.

Tailwind CSS是一个CSS框架,但与大多数其他框架(如Bootstrap,Material或Ant Design)不同。 这是一个实用程序优先的框架,这意味着它不关注按钮,卡片和警报等预先设计的组件。 它提供了低级实用程序类,使您无需离开HTML即可构建完全自定义的设计。

Although it requires some time to learn all the utility classes, you barely need to write any CSS anymore once you start using it. It can give you a huge boost in productivity, and not needing to switch files while styling your HTML elements can feel like a blessing.

尽管学习所有实用程序类需要花费一些时间,但是一旦开始使用它,您几乎不需要再编写任何CSS。 它可以极大地提高您的生产力,并且在样式化HTML元素时无需切换文件就可以了。

开始吧 (Let’s Start)

If you haven’t got a project set up with Next.js, first open your terminal and run yarn create next-app in your projects folder.

如果您尚未使用Next.js设置项目,请首先打开终端并在projects文件夹中运行yarn create next-app Create yarn create next-app

You will get prompted with the following message:

您将收到以下消息的提示:

What is your project named?

Fill in a name and hit enter. The next message will be:

填写名称,然后按Enter。 下一条消息将是:

Pick a template

Choose “Default starter app” and wait until your project is ready. Then, type cd to make sure you are inside that directory where you can run yarn dev to start the development server. You should now have your new Next.js project up and running.

选择“默认入门应用程序”,然后等待您的项目准备就绪。 然后,键入cd 以确保您位于该目录中,您可以在其中运行yarn dev启动开发服务器。 现在,您应该启动并运行新的Next.js项目。

添加Tailwind CSS (Adding Tailwind CSS)

Start by adding the Tailwind CSS library to your development dependencies using npm or yarn:

首先使用npm或yarn将Tailwind CSS库添加到您的开发依赖项中:

yarn add tailwindcss -D

Then, we need to add a tailwind.config.js file to the root of our application. Use the following command to set this up:

然后,我们需要将tailwind.config.js文件添加到应用程序的根目录。 使用以下命令进行设置:

npx tailwind init

You should now have a tailwind.config.js in your project containing the following:

现在,您的项目中应该包含一个tailwind.config.js ,其中应包含以下内容:

module.exports = {
  purge: [],
  theme: {
    extend: {},
  },
  variants: {},
  plugins: [],
}

添加PostCSS (Adding PostCSS)

Next up, we need to configure PostCSS, a tool for transforming CSS with JavaScript because Tailwind CSS is a PostCSS plug-in. Let’s create a postcss.config.js and add the following so Next.js will load the defined plug-ins.

接下来,我们需要配置PostCSS ,这是一种使用JavaScript转换CSS的工具,因为Tailwind CSS是PostCSS插件。 让我们创建一个postcss.config.js并添加以下内容,以便Next.js加载定义的插件。

In the root of your project, run:

在项目的根目录中,运行:

touch postcss.config.js

Then add the following to that file:

然后将以下内容添加到该文件:

module.exports = {
         
plugins: ['tailwindcss'],
}

Besides TailwindCSS, we should also add the PostCSS Preset Env module, which converts modern CSS into something most browsers understand:

除了TailwindCSS,我们还应该添加PostCSS Preset Env模块,该模块将现代CSS转换为大多数浏览器可以理解的东西:

yarn add postcss-preset-env -D

Now let’s update our postcss.config.js to include this module:

现在,让我们更新postcss.config.js使其包含以下模块:

module.exports = {
         
plugins: ['tailwindcss', 'postcss-preset-env'],
}

Now let’s create a styles folder and import Tailwind CSS from a CSS file:

现在让我们创建一个styles文件夹,并从CSS文件导入Tailwind CSS:

mkdir styles touch styles/tailwind.css

Inside tailwind.css:

tailwind.css内部:

@tailwind base;
@tailwind components;
@tailwind utilities;

To add global CSS to a Next.js app, we need to override the default App component. Next.js uses the App component to initialize pages, and if we need to control the page initialization, we need to create a file called pages/_app.js:

要将全局CSS添加到Next.js应用程序,我们需要覆盖默认的App组件。 Next.js使用App组件初始化页面,如果需要控制页面初始化,则需要创建一个名为pages/_app.js的文件:

touch pages/_app.js

Now import the stylesheet we created:

现在导入我们创建的样式表:

import '../styles/tailwind.css';export default function MyApp({ Component, pageProps }) {
         
return ;
}

Cool, now we are ready to add some Tailwind CSS magic to our home page. Go to /pages/index.js (or /pages/index.tsx if you use TypeScript) and add some elements with Tailwind CSS classes. For example:

太酷了,现在我们可以为我们的主页添加一些Tailwind CSS魔术了。 转到/pages/index.js (或/pages/index.tsx如果您使用的打字稿),并添加有顺风CSS类的一些元素。 例如:

export default function Home() {
  return (
    

Jake Prins

JavaScript developer
Twitter: @jakeprins_nl
www.jakeprins.com
); }

Run yarn dev to see your app on http://localhost:3000 in your browser.

运行yarn dev在浏览器中的http://localhost:3000上查看您的应用程序。

清除CSS (PurgeCSS)

One problem with Tailwind CSS is the large file size, but we can use PurgeCSS to fix this. PurgeCSS reduces the file size by scanning your HTML and removing any classes that aren’t used. We only want this in production because if we are developing, we want to be able to use any Tailwind CSS class without running the build process. To set this up, we start by installing the PurgeCSS module as a dev dependency in our project:

Tailwind CSS的一个问题是文件大,但是我们可以使用PurgeCSS来解决此问题。 PurgeCSS通过扫描HTML并删除所有未使用的类来减小文件大小。 我们只想在生产中使用它,因为如果我们正在开发,我们希望能够使用任何Tailwind CSS类而无需运行构建过程。 要进行设置,我们首先将PurgeCSS模块安装为项目中的开发依赖项:

yarn add @fullhuman/postcss-purgecss -D

Then update your postcss.config.js file with the following code:

然后,使用以下代码更新postcss.config.js文件:

const purgecss = [
  '@fullhuman/postcss-purgecss',
  {
    // Specify the paths to all of the template files
    content: [
      './pages/**/*.{js,jsx,ts,tsx}',
      './components/**/*.{js,jsx,ts,tsx}',
    ],
    // This is the function used to extract class names from the templates
    defaultExtractor: (content) => {
      // Capture as liberally as possible, including things like `h-(screen-1.5)`
      const broadMatches = content.match(/[^<>"'`\\s]*[^<>"'`\\s:]/g) || [];
      // Capture classes within other delimiters like .block(class="w-1/2") in Pug
      const innerMatches = content.match(/[^<>"'`\\s.()]*[^<>"'`\\s.():]/g) || [];
      return broadMatches.concat(innerMatches);
    },
  },
];
module.exports = {
  plugins: [
    'tailwindcss',
    process.env.NODE_ENV === 'production' ? purgecss : undefined,
    'postcss-preset-env',
  ],
};

The order of exports matters. First, we tell PostCSS to load Tailwind CSS. Then, we purge the unused CSS (only in production). Finally, we let the PostCSS Preset Env plug-in do its thing to make the remaining CSS compatible for all browsers.

出口顺序很重要。 首先,我们告诉PostCSS加载Tailwind CSS。 然后,我们清除未使用CSS(仅在生产中)。 最后,我们让PostCSS Preset Env插件完成其工作,以使其余CSS与所有浏览器兼容。

For now, we check all of our code inside .js, .jsx, .ts or .tsx files that live in either the pages/ or components/ folder. If you plan to add HTML in other folders like containers/ or something, make sure you add that folder to this configuration file.

现在,我们检查位于pages/components/文件夹中的.js, .jsx, .ts or .tsx文件中的所有代码。 如果您打算将HTML添加到其他文件夹(如containers/或其他内容)中,请确保将该文件夹添加到此配置文件中。

Finally, it’s recommended to only apply PurgeCSS to Tailwind CSS’s utility classes — not to base styles or component classes. This will ensure you don’t accidentally purge important base styles when working with Next.js The easiest way to do this is to use PurgeCSS’s whitelisting feature to disable PurgeCSS for non-utility classes. Add this to your tailwind.css file:

最后,建议仅将PurgeCSS应用于Tailwind CSS的实用程序类,而不应用于基本样式或组件类 。 这将确保您在使用Next.js时不会意外清除重要的基本样式。最简单的方法是使用PurgeCSS的白名单功能为非实用程序类禁用PurgeCSS。 将此添加到您的tailwind.css文件中:

/* purgecss start ignore */
@tailwind base;
@tailwind components;
/* purgecss end ignore */@tailwind utilities;

Cool, now we are ready to work with Next.js and Tailwind CSS without having to worry about bundle sizes!

太好了,现在我们可以使用Next.js和Tailwind CSS了,而不必担心捆绑包的大小!

That’s it! Thanks for reading. I hope it was helpful.

而已! 谢谢阅读。 希望对您有所帮助。

翻译自: https://medium.com/better-programming/how-to-set-up-next-js-with-tailwind-css-b93ccd2d4164

tailwind css

你可能感兴趣的:(python)