狼叔来找翻译人员了--plato--持续翻译中.....

这个项目是使用 Create React App引导的。

你将在下面找到如何执行常见任务的一些信息。

你可以在这找到最新版本的指南。

目录

  • 更新到新版本
  • 发送反馈
  • 文件夹结构
  • 可用的脚本
    • npm start
    • npm test
    • npm run build
    • npm run eject
  • 支持的浏览器
  • 支持的语言功能
  • 编辑器中语法高亮
  • 编辑器中显示Lint输出
  • 编辑器中进行调试
  • 自动化格式代码
  • 改变页面 </code></li> <li>安装依赖项</li> <li>导入组件</li> <li>代码拆分</li> <li>添加样式表</li> <li>添加CSS模块样式表</li> <li>添加Sass样式表</li> <li>后处理CSS</li> <li>添加图像,字体和文件</li> <li>添加SVG</li> <li>使用 <code>public</code> 文件夹 <ul> <li>更改HTML</li> <li>在模块系统外添加资源</li> <li>何时使用 <code>public</code> 文件夹</li> </ul> </li> <li>使用全局变量</li> <li>添加 Bootstrap <ul> <li>使用自定义主题</li> </ul> </li> <li>添加流</li> <li>添加中继</li> <li>添加路由器</li> <li>添加自定义环境变量 <ul> <li>在HTML中引用环境变量</li> <li>在Shell中添加临时环境变量</li> <li>添加开发环境变量 <code>.env</code></li> </ul> </li> <li>我可以使用装饰器吗?</li> <li>使用AJAX请求获取数据</li> <li>与后端API集成 <ul> <li>Node</li> <li>Ruby on Rails</li> </ul> </li> <li>在开发中代理API请求 <ul> <li>配置代理后出现“无效主机标头”错误</li> <li>手动配置代理</li> </ul> </li> <li>在开发中使用HTTPS</li> <li>在服务器上生成动态标签 <code><meta></code> </li> <li>预渲染HTML静态文件</li> <li>将数据从服务器注入页面</li> <li>运行测试 <ul> <li>文件名约定</li> <li>命令行界面</li> <li>版本控制集成</li> <li>写测试</li> <li>测试组件</li> <li>使用第三方断言库</li> <li>初始化测试环境</li> <li>聚焦和排除第三方环境</li> <li>覆盖率报告</li> <li>持续集成</li> <li>禁用jsdom</li> <li>快照测试</li> <li>编辑器集成</li> </ul> </li> <li>调试测试 <ul> <li>在Chrome中调试测试</li> <li>在Visual Studio Code中调试测试</li> </ul> </li> <li>隔离开发组件 <ul> <li>由Storybook开始</li> <li>由Styleguidist开始</li> </ul> </li> <li>发布组件到npm</li> <li>做渐进式Web应用程序 <ul> <li>为什么选择加入?</li> <li>离线优考虑因素</li> <li>渐进式Web应用程序元数据</li> </ul> </li> <li>分析Bundle大小</li> <li>部署 <ul> <li>静态服务器</li> <li>其他方案</li> <li>使用客户端路由提供应用支持</li> <li>相对路径构建</li> <li>为任意构建环境定制环境变量</li> <li>Azure</li> <li>Firebase</li> <li>GitHub Pages</li> <li>Heroku</li> <li>Netlify</li> <li>Now</li> <li>S3 and CloudFront</li> <li>Surge</li> </ul> </li> <li>高级配置</li> <li>故障排除 <ul> <li><code>npm start</code> 没有检测到变化</li> <li><code>npm test</code> 在macOS Sierra上挂起或崩溃</li> <li><code>npm run build</code> 过早退出</li> <li><code>npm run build</code> Heroku失败</li> <li><code>npm run build</code> 压缩失败</li> <li>缺少Moment.js环境</li> </ul> </li> <li>Ejecting替代品</li> <li>有什么遗漏?</li> </ul> <h3>更新到新版本</h3> <p>Create React App分为两个包:</p> <ul> <li><code>create-react-app</code> 是一个全局命令行实用程序,可用于创建新项目。</li> <li><code>react-scripts</code> 是生成的项目中的开发依赖项(包括此项)。</li> </ul> <p>你几乎从不需要更新<code>create-react-app</code> : 它将所有设置委托给 <code>react-scripts</code>.</p> <p>当你运行 <code>create-react-app</code>时, 它总是实用 <code>react-scripts</code>的最新版本创建项目,因此你将自动获得新创建的应用程序中所有功能和改进。.</p> <p>更新现有项目到一个新版本的 <code>react-scripts</code>,打开更改日志,找到你当前所在的版本 (如果你不确定可以在在文件中检查 <code>package.json</code> ),并应用新版本的迁移说明。</p> <p>在大多数情况下自底向上模块化程序设计在<code>package.json</code> 的 <code>react-scripts</code> 版本并运行 <code>npm install</code> (或者 <code>yarn install</code>) 在这个文件夹中已经足够了,但最好查看 更改日志 以了解可能发生的重大变化。</p> <p>我们承诺将破坏性保持在最低限度,一遍您可以轻松升级<code>react-scripts</code> 。</p> <h3>发送反馈</h3> <p>我们随时欢迎 您的反馈.</p> <h3>文件夹结构</h3> <p>创建后,您的项目应如下所示:</p> <pre><code>my-app/ README.md node_modules/ package.json public/ index.html favicon.ico src/ App.css App.js App.test.js index.css index.js logo.svg </code></pre> <p>对于要构建的目录, <strong>这些文件必须与确切的文件名一起存在</strong>:</p> <ul> <li><code>public/index.html</code> 这是页面模版;</li> <li><code>src/index.js</code> 是JavaScript的入口点。</li> </ul> <p>您可以删除或重命名其他文件。</p> <p>您可以在 <code>src</code>里面创建子目录。 为了加快重建的速度, 只有在 <code>src</code>里的文件被WebPack处理。<br><br> 你需要<strong>把任何JS和CSS文件放在<code>src</code>里面</strong>,否则WebPack不会看到他们。</p> <p>只有在<code>public</code>里的文件能够从<code>public/index.html</code>被使用。<br><br> 阅读以下有关使用JavaScript和HTML资源的说明</p> <p>但是,您可以创建更多顶级目录。<br><br> 它们不会包含在生产版本中,因此您可以将它们用于文档等内容。</p> <p>如果您安装了Git并且您的项目不是更大的存储库的一部分,那么将初始化一个新的存储库,从而产生一个额外的 <code>.git/</code>顶级目录。</p> <h3>可用的脚本</h3> <p>在项目目录中,您可以运行:</p> <h4><code>npm start</code></h4> <p>在开发模式下运行应用程序。<br><br> 打开http://localhost:3000在浏览器中查看它。</p> <p>如果您进行编辑,页面将重新加载。<br><br> 您还将在控制台中看到任何lint错误。</p> <h4><code>npm test</code></h4> <p>以交互式监视模式启动测试运行器。<br><br> 有关更多信息,请参阅有关运行测试的部分。</p> <h4><code>npm run build</code></h4> <p>构建用于生产的应用程序到<code>build</code>文件夹。<br><br> 它正确地将React捆绑在生产模式中并优化构建以获得最佳性能。</p> <p>构建被压缩,文件名包含哈希。<br><br> 您的应用已准备好部署!</p> <p>有关更多信息,请参阅有关部署的部分。</p> <h4><code>npm run eject</code></h4> <p><strong>注意:这是一个单项操作,一旦 <code>eject</code>,你就不能回去!</strong></p> <p>如果您对构建工具和配置选择不满意,您可以随时<code>eject</code>。 此命令将从项目中删除单个构建依赖项。</p> <p>相反,它会将所有配置文件和传递依赖项(Webpack,Babel,ESLint等)复制到项目中,以便您可以完全控制它们。所有的命令除了<code>eject</code>之外将仍然有效,但它们将指向复制的脚本,以便您可以调整它们。在这一点上,你是独立的。</p> <p>你不必使用<code>eject</code>。精选功能集适用于中小型部署,您不应觉得有义务使用此功能。 但是,我们知道如果您准备好它时无法自定义此工具将无用。</p> <h3>支持的浏览器</h3> <p>默认情况下,生成的项目支持所有现代浏览器。<br><br> 对Internet Explorer 9,10和11的支持需要polyfills.</p> <h4>支持的语言功能</h4> <p>该项目支持最新JavaScript标准的超集。<br><br> 除了ES6语法功能外,它还支持:</p> <ul> <li>Exponentiation Operator (ES2016).</li> <li>Async/await (ES2017).</li> <li>Object Rest/Spread Properties (ES2018).</li> <li>Dynamic import() (stage 3 proposal)</li> <li>Class Fields and Static Properties (part of stage 3 proposal).</li> <li>JSX and Flow syntax.</li> </ul> <p>Learn more about different proposal stages.</p> <p>While we recommend using experimental proposals with some caution, Facebook heavily uses these features in the product code, so we intend to provide codemods if any of these proposals change in the future.</p> <p>Note that <strong>this project includes no polyfills</strong> by default.</p> <p>If you use any other ES6+ features that need <strong>runtime support</strong> (such as <code>Array.from()</code> or <code>Symbol</code>), make sure you are including the appropriate polyfills manually, or that the browsers you are targeting already support them.</p> <h3>Syntax Highlighting in the Editor</h3> <p>To configure the syntax highlighting in your favorite text editor, head to the relevant Babel documentation page and follow the instructions. Some of the most popular editors are covered.</p> <h3>Displaying Lint Output in the Editor</h3> <blockquote> <p>Note: this feature is available with <code>react-scripts@0.2.0</code> and higher.<br><br> It also only works with npm 3 or higher.</p> </blockquote> <p>Some editors, including Sublime Text, Atom, and Visual Studio Code, provide plugins for ESLint.</p> <p>They are not required for linting. You should see the linter output right in your terminal as well as the browser console. However, if you prefer the lint results to appear right in your editor, there are some extra steps you can do.</p> <p>You would need to install an ESLint plugin for your editor first. Then, add a file called <code>.eslintrc</code> to the project root:</p> <pre><code class="prism language-js"><span class="token punctuation">{</span> <span class="token string">"extends"</span><span class="token punctuation">:</span> <span class="token string">"react-app"</span> <span class="token punctuation">}</span> </code></pre> <p>Now your editor should report the linting warnings.</p> <p>Note that even if you edit your <code>.eslintrc</code> file further, these changes will <strong>only affect the editor integration</strong>. They won’t affect the terminal and in-browser lint output. This is because Create React App intentionally provides a minimal set of rules that find common mistakes.</p> <p>If you want to enforce a coding style for your project, consider using Prettier instead of ESLint style rules.</p> <h3>Debugging in the Editor</h3> <p><strong>This feature is currently only supported by Visual Studio Code and WebStorm.</strong></p> <p>Visual Studio Code and WebStorm support debugging out of the box with Create React App. This enables you as a developer to write and debug your React code without leaving the editor, and most importantly it enables you to have a continuous development workflow, where context switching is minimal, as you don’t have to switch between tools.</p> <h4>Visual Studio Code</h4> <p>You would need to have the latest version of VS Code and VS Code Chrome Debugger Extension installed.</p> <p>Then add the block below to your <code>launch.json</code> file and put it inside the <code>.vscode</code> folder in your app’s root directory.</p> <pre><code class="prism language-json"><span class="token punctuation">{</span> <span class="token string">"version"</span><span class="token punctuation">:</span> <span class="token string">"0.2.0"</span><span class="token punctuation">,</span> <span class="token string">"configurations"</span><span class="token punctuation">:</span> <span class="token punctuation">[</span> <span class="token punctuation">{</span> <span class="token string">"name"</span><span class="token punctuation">:</span> <span class="token string">"Chrome"</span><span class="token punctuation">,</span> <span class="token string">"type"</span><span class="token punctuation">:</span> <span class="token string">"chrome"</span><span class="token punctuation">,</span> <span class="token string">"request"</span><span class="token punctuation">:</span> <span class="token string">"launch"</span><span class="token punctuation">,</span> <span class="token string">"url"</span><span class="token punctuation">:</span> <span class="token string">"http://localhost:3000"</span><span class="token punctuation">,</span> <span class="token string">"webRoot"</span><span class="token punctuation">:</span> <span class="token string">"${workspaceRoot}/src"</span><span class="token punctuation">,</span> <span class="token string">"sourceMapPathOverrides"</span><span class="token punctuation">:</span> <span class="token punctuation">{</span> <span class="token string">"webpack:///src/*"</span><span class="token punctuation">:</span> <span class="token string">"${webRoot}/*"</span> <span class="token punctuation">}</span> <span class="token punctuation">}</span> <span class="token punctuation">]</span> <span class="token punctuation">}</span> </code></pre> <blockquote> <p>Note: the URL may be different if you’ve made adjustments via the HOST or PORT environment variables.</p> </blockquote> <p>Start your app by running <code>npm start</code>, and start debugging in VS Code by pressing <code>F5</code> or by clicking the green debug icon. You can now write code, set breakpoints, make changes to the code, and debug your newly modified code—all from your editor.</p> <p>Having problems with VS Code Debugging? Please see their troubleshooting guide.</p> <h4>WebStorm</h4> <p>You would need to have WebStorm and JetBrains IDE Support Chrome extension installed.</p> <p>In the WebStorm menu <code>Run</code> select <code>Edit Configurations...</code>. Then click <code>+</code> and select <code>JavaScript Debug</code>. Paste <code>http://localhost:3000</code> into the URL field and save the configuration.</p> <blockquote> <p>Note: the URL may be different if you’ve made adjustments via the HOST or PORT environment variables.</p> </blockquote> <p>Start your app by running <code>npm start</code>, then press <code>^D</code> on macOS or <code>F9</code> on Windows and Linux or click the green debug icon to start debugging in WebStorm.</p> <p>The same way you can debug your application in IntelliJ IDEA Ultimate, PhpStorm, PyCharm Pro, and RubyMine.</p> <h3>Formatting Code Automatically</h3> <p>Prettier is an opinionated code formatter with support for JavaScript, CSS and JSON. With Prettier you can format the code you write automatically to ensure a code style within your project. See the Prettier’s GitHub page for more information, and look at this page to see it in action.</p> <p>To format our code whenever we make a commit in git, we need to install the following dependencies:</p> <pre><code class="prism language-sh">npm install --save husky lint-staged prettier </code></pre> <p>Alternatively you may use <code>yarn</code>:</p> <pre><code class="prism language-sh">yarn add husky lint-staged prettier </code></pre> <ul> <li><code>husky</code> makes it easy to use githooks as if they are npm scripts.</li> <li><code>lint-staged</code> allows us to run scripts on staged files in git. See this blog post about lint-staged to learn more about it.</li> <li><code>prettier</code> is the JavaScript formatter we will run before commits.</li> </ul> <p>Now we can make sure every file is formatted correctly by adding a few lines to the <code>package.json</code> in the project root.</p> <p>Add the following field to the <code>package.json</code> section:</p> <pre><code class="prism language-diff">+ "husky": { + "hooks": { + "pre-commit": "lint-staged" + } + } </code></pre> <p>Next we add a ‘lint-staged’ field to the <code>package.json</code>, for example:</p> <pre><code class="prism language-diff"> "dependencies": { // ... }, + "lint-staged": { + "src/**/*.{js,jsx,json,css}": [ + "prettier --single-quote --write", + "git add" + ] + }, "scripts": { </code></pre> <p>Now, whenever you make a commit, Prettier will format the changed files automatically. You can also run <code>./node_modules/.bin/prettier --single-quote --write "src/**/*.{js,jsx}"</code> to format your entire project for the first time.</p> <p>Next you might want to integrate Prettier in your favorite editor. Read the section on Editor Integration on the Prettier GitHub page.</p> <h3>Changing the Page <code><title></code></h3> <p>You can find the source HTML file in the <code>public</code> folder of the generated project. You may edit the <code><title></code> tag in it to change the title from “React App” to anything else.</p> <p>Note that normally you wouldn’t edit files in the <code>public</code> folder very often. For example, adding a stylesheet is done without touching the HTML.</p> <p>If you need to dynamically update the page title based on the content, you can use the browser <code>document.title</code> API. For more complex scenarios when you want to change the title from React components, you can use React Helmet, a third party library.</p> <p>If you use a custom server for your app in production and want to modify the title before it gets sent to the browser, you can follow advice in this section. Alternatively, you can pre-build each page as a static HTML file which then loads the JavaScript bundle, which is covered here.</p> <h3>Installing a Dependency</h3> <p>The generated project includes React and ReactDOM as dependencies. It also includes a set of scripts used by Create React App as a development dependency. You may install other dependencies (for example, React Router) with <code>npm</code>:</p> <pre><code class="prism language-sh">npm install --save react-router-dom </code></pre> <p>Alternatively you may use <code>yarn</code>:</p> <pre><code class="prism language-sh">yarn add react-router-dom </code></pre> <p>This works for any library, not just <code>react-router-dom</code>.</p> <h3>Importing a Component</h3> <p>This project setup supports ES6 modules thanks to Webpack.<br><br> While you can still use <code>require()</code> and <code>module.exports</code>, we encourage you to use <code>import</code> and <code>export</code> instead.</p> <p>For example:</p> <h4><code>Button.js</code></h4> <pre><code class="prism language-js"><span class="token keyword">import</span> React<span class="token punctuation">,</span> <span class="token punctuation">{</span> Component <span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">'react'</span><span class="token punctuation">;</span> <span class="token keyword">class</span> <span class="token class-name">Button</span> <span class="token keyword">extends</span> <span class="token class-name">Component</span> <span class="token punctuation">{</span> <span class="token function">render</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span> <span class="token comment">// ...</span> <span class="token punctuation">}</span> <span class="token punctuation">}</span> <span class="token keyword">export</span> <span class="token keyword">default</span> Button<span class="token punctuation">;</span> <span class="token comment">// Don’t forget to use export default!</span> </code></pre> <h4><code>DangerButton.js</code></h4> <pre><code class="prism language-js"><span class="token keyword">import</span> React<span class="token punctuation">,</span> <span class="token punctuation">{</span> Component <span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">'react'</span><span class="token punctuation">;</span> <span class="token keyword">import</span> Button <span class="token keyword">from</span> <span class="token string">'./Button'</span><span class="token punctuation">;</span> <span class="token comment">// Import a component from another file</span> <span class="token keyword">class</span> <span class="token class-name">DangerButton</span> <span class="token keyword">extends</span> <span class="token class-name">Component</span> <span class="token punctuation">{</span> <span class="token function">render</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span> <span class="token keyword">return</span> <span class="token operator"><</span>Button color<span class="token operator">=</span><span class="token string">"red"</span> <span class="token operator">/</span><span class="token operator">></span><span class="token punctuation">;</span> <span class="token punctuation">}</span> <span class="token punctuation">}</span> <span class="token keyword">export</span> <span class="token keyword">default</span> DangerButton<span class="token punctuation">;</span> </code></pre> <p>Be aware of the difference between default and named exports. It is a common source of mistakes.</p> <p>We suggest that you stick to using default imports and exports when a module only exports a single thing (for example, a component). That’s what you get when you use <code>export default Button</code> and <code>import Button from './Button'</code>.</p> <p>Named exports are useful for utility modules that export several functions. A module may have at most one default export and as many named exports as you like.</p> <p>Learn more about ES6 modules:</p> <ul> <li>When to use the curly braces?</li> <li>Exploring ES6: Modules</li> <li>Understanding ES6: Modules</li> </ul> <h3>Code Splitting</h3> <p>Instead of downloading the entire app before users can use it, code splitting allows you to split your code into small chunks which you can then load on demand.</p> <p>This project setup supports code splitting via dynamic <code>import()</code>. Its proposal is in stage 3. The <code>import()</code> function-like form takes the module name as an argument and returns a <code>Promise</code> which always resolves to the namespace object of the module.</p> <p>Here is an example:</p> <h4><code>moduleA.js</code></h4> <pre><code class="prism language-js"><span class="token keyword">const</span> moduleA <span class="token operator">=</span> <span class="token string">'Hello'</span><span class="token punctuation">;</span> <span class="token keyword">export</span> <span class="token punctuation">{</span> moduleA <span class="token punctuation">}</span><span class="token punctuation">;</span> </code></pre> <h4><code>App.js</code></h4> <pre><code class="prism language-js"><span class="token keyword">import</span> React<span class="token punctuation">,</span> <span class="token punctuation">{</span> Component <span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">'react'</span><span class="token punctuation">;</span> <span class="token keyword">class</span> <span class="token class-name">App</span> <span class="token keyword">extends</span> <span class="token class-name">Component</span> <span class="token punctuation">{</span> <span class="token function-variable function">handleClick</span> <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span> <span class="token keyword">import</span><span class="token punctuation">(</span><span class="token string">'./moduleA'</span><span class="token punctuation">)</span> <span class="token punctuation">.</span><span class="token function">then</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">{</span> moduleA <span class="token punctuation">}</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span> <span class="token comment">// Use moduleA</span> <span class="token punctuation">}</span><span class="token punctuation">)</span> <span class="token punctuation">.</span><span class="token keyword">catch</span><span class="token punctuation">(</span>err <span class="token operator">=></span> <span class="token punctuation">{</span> <span class="token comment">// Handle failure</span> <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">}</span><span class="token punctuation">;</span> <span class="token function">render</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span> <span class="token keyword">return</span> <span class="token punctuation">(</span> <span class="token operator"><</span>div<span class="token operator">></span> <span class="token operator"><</span>button onClick<span class="token operator">=</span><span class="token punctuation">{</span><span class="token keyword">this</span><span class="token punctuation">.</span>handleClick<span class="token punctuation">}</span><span class="token operator">></span>Load<span class="token operator"><</span><span class="token operator">/</span>button<span class="token operator">></span> <span class="token operator"><</span><span class="token operator">/</span>div<span class="token operator">></span> <span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">}</span> <span class="token punctuation">}</span> <span class="token keyword">export</span> <span class="token keyword">default</span> App<span class="token punctuation">;</span> </code></pre> <p>This will make <code>moduleA.js</code> and all its unique dependencies as a separate chunk that only loads after the user clicks the ‘Load’ button.</p> <p>You can also use it with <code>async</code> / <code>await</code> syntax if you prefer it.</p> <h4>With React Router</h4> <p>If you are using React Router check out this tutorial on how to use code splitting with it. You can find the companion GitHub repository here.</p> <p>Also check out the Code Splitting section in React documentation.</p> <h3>Adding a Stylesheet</h3> <p>This project setup uses Webpack for handling all assets. Webpack offers a custom way of “extending” the concept of <code>import</code> beyond JavaScript. To express that a JavaScript file depends on a CSS file, you need to <strong>import the CSS from the JavaScript file</strong>:</p> <h4><code>Button.css</code></h4> <pre><code class="prism language-css"><span class="token selector">.Button</span> <span class="token punctuation">{</span> <span class="token property">padding</span><span class="token punctuation">:</span> 20px<span class="token punctuation">;</span> <span class="token punctuation">}</span> </code></pre> <h4><code>Button.js</code></h4> <pre><code class="prism language-js"><span class="token keyword">import</span> React<span class="token punctuation">,</span> <span class="token punctuation">{</span> Component <span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">'react'</span><span class="token punctuation">;</span> <span class="token keyword">import</span> <span class="token string">'./Button.css'</span><span class="token punctuation">;</span> <span class="token comment">// Tell Webpack that Button.js uses these styles</span> <span class="token keyword">class</span> <span class="token class-name">Button</span> <span class="token keyword">extends</span> <span class="token class-name">Component</span> <span class="token punctuation">{</span> <span class="token function">render</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span> <span class="token comment">// You can use them as regular CSS styles</span> <span class="token keyword">return</span> <span class="token operator"><</span>div className<span class="token operator">=</span><span class="token string">"Button"</span> <span class="token operator">/</span><span class="token operator">></span><span class="token punctuation">;</span> <span class="token punctuation">}</span> <span class="token punctuation">}</span> </code></pre> <p><strong>This is not required for React</strong> but many people find this feature convenient. You can read about the benefits of this approach here. However you should be aware that this makes your code less portable to other build tools and environments than Webpack.</p> <p>In development, expressing dependencies this way allows your styles to be reloaded on the fly as you edit them. In production, all CSS files will be concatenated into a single minified <code>.css</code> file in the build output.</p> <p>If you are concerned about using Webpack-specific semantics, you can put all your CSS right into <code>src/index.css</code>. It would still be imported from <code>src/index.js</code>, but you could always remove that import if you later migrate to a different build tool.</p> <h3>Adding a CSS Modules Stylesheet</h3> <blockquote> <p>Note: this feature is available with <code>react-scripts@2.0.0</code> and higher.</p> </blockquote> <p>This project supports CSS Modules alongside regular stylesheets using the <code>[name].module.css</code> file naming convention. CSS Modules allows the scoping of CSS by automatically creating a unique classname of the format <code>[filename]\_[classname]\_\_[hash]</code>.</p> <blockquote> <p><strong>Tip:</strong> Should you want to preprocess a stylesheet with Sass then make sure to follow the installation instructions and then change the stylesheet file extension as follows: <code>[name].module.scss</code> or <code>[name].module.sass</code>.</p> </blockquote> <p>CSS Modules let you use the same CSS class name in different files without worrying about naming clashes. Learn more about CSS Modules here.</p> <h4><code>Button.module.css</code></h4> <pre><code class="prism language-css"><span class="token selector">.error</span> <span class="token punctuation">{</span> <span class="token property">background-color</span><span class="token punctuation">:</span> red<span class="token punctuation">;</span> <span class="token punctuation">}</span> </code></pre> <h4><code>another-stylesheet.css</code></h4> <pre><code class="prism language-css"><span class="token selector">.error</span> <span class="token punctuation">{</span> <span class="token property">color</span><span class="token punctuation">:</span> red<span class="token punctuation">;</span> <span class="token punctuation">}</span> </code></pre> <h4><code>Button.js</code></h4> <pre><code class="prism language-js"><span class="token keyword">import</span> React<span class="token punctuation">,</span> <span class="token punctuation">{</span> Component <span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">'react'</span><span class="token punctuation">;</span> <span class="token keyword">import</span> styles <span class="token keyword">from</span> <span class="token string">'./Button.module.css'</span><span class="token punctuation">;</span> <span class="token comment">// Import css modules stylesheet as styles</span> <span class="token keyword">import</span> <span class="token string">'./another-stylesheet.css'</span><span class="token punctuation">;</span> <span class="token comment">// Import regular stylesheet</span> <span class="token keyword">class</span> <span class="token class-name">Button</span> <span class="token keyword">extends</span> <span class="token class-name">Component</span> <span class="token punctuation">{</span> <span class="token function">render</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span> <span class="token comment">// reference as a js object</span> <span class="token keyword">return</span> <span class="token operator"><</span>button className<span class="token operator">=</span><span class="token punctuation">{</span>styles<span class="token punctuation">.</span>error<span class="token punctuation">}</span><span class="token operator">></span>Error Button<span class="token operator"><</span><span class="token operator">/</span>button<span class="token operator">></span><span class="token punctuation">;</span> <span class="token punctuation">}</span> <span class="token punctuation">}</span> </code></pre> <h4>Result</h4> <p>No clashes from other <code>.error</code> class names</p> <pre><code class="prism language-html"><span class="token comment"><!-- This button has red background but not red text --></span> <span class="token tag"><span class="token tag"><span class="token punctuation"><</span>button</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>Button_error_ax7yz<span class="token punctuation">"</span></span><span class="token punctuation">></span></span><span class="token tag"><span class="token tag"><span class="token punctuation"></</span>div</span><span class="token punctuation">></span></span> </code></pre> <p><strong>This is an optional feature.</strong> Regular <code><link></code> stylesheets and CSS files are fully supported. CSS Modules are turned on for files ending with the <code>.module.css</code> extension.</p> <h3>Adding a Sass Stylesheet</h3> <blockquote> <p>Note: this feature is available with <code>react-scripts@2.0.0</code> and higher.</p> </blockquote> <p>Generally, we recommend that you don’t reuse the same CSS classes across different components. For example, instead of using a <code>.Button</code> CSS class in <code><AcceptButton></code> and <code><RejectButton></code> components, we recommend creating a <code><Button></code> component with its own <code>.Button</code> styles, that both <code><AcceptButton></code> and <code><RejectButton></code> can render (but not inherit).</p> <p>Following this rule often makes CSS preprocessors less useful, as features like mixins and nesting are replaced by component composition. You can, however, integrate a CSS preprocessor if you find it valuable.</p> <p>To use Sass, first install <code>node-sass</code>:</p> <pre><code class="prism language-bash">$ <span class="token function">npm</span> <span class="token function">install</span> node-sass --save $ <span class="token comment"># or</span> $ yarn add node-sass </code></pre> <p>Now you can rename <code>src/App.css</code> to <code>src/App.scss</code> and update <code>src/App.js</code> to import <code>src/App.scss</code>.<br> This file and any other file will be automatically compiled if imported with the extension <code>.scss</code> or <code>.sass</code>.</p> <p>To share variables between Sass files, you can use Sass imports. For example, <code>src/App.scss</code> and other component style files could include <code>@import "./shared.scss";</code> with variable definitions.</p> <p>This will allow you to do imports like</p> <pre><code class="prism language-scss">@import 'styles/_colors.scss'; // assuming a styles directory under src/ @import '~nprogress/nprogress'; // importing a css file from the nprogress node module </code></pre> <blockquote> <p><strong>Tip:</strong> You can opt into using this feature with CSS modules too!</p> </blockquote> <blockquote> <p><strong>Note:</strong> You must prefix imports from <code>node_modules</code> with <code>~</code> as displayed above.</p> </blockquote> <blockquote> <p><strong>Note:</strong> If you’re using Flow, add the following to your <code>.flowconfig</code> so it’ll recognize the <code>.sass</code> or <code>.scss</code> imports.</p> </blockquote> <pre><code>[options] module.file_ext=.sass module.file_ext=.scss </code></pre> <h3>Post-Processing CSS</h3> <p>This project setup minifies your CSS and adds vendor prefixes to it automatically through Autoprefixer so you don’t need to worry about it.</p> <p>Support for new CSS features like the <code>all</code> property, <code>break</code> properties, custom properties, and media query ranges are automatically polyfilled to add support for older browsers.</p> <p>You can customize your target support browsers by adjusting the <code>browserslist</code> key in <code>package.json</code> according to the Browserslist specification.</p> <p>For example, this:</p> <pre><code class="prism language-css"><span class="token selector">.App</span> <span class="token punctuation">{</span> <span class="token property">display</span><span class="token punctuation">:</span> flex<span class="token punctuation">;</span> <span class="token property">flex-direction</span><span class="token punctuation">:</span> row<span class="token punctuation">;</span> <span class="token property">align-items</span><span class="token punctuation">:</span> center<span class="token punctuation">;</span> <span class="token punctuation">}</span> </code></pre> <p>becomes this:</p> <pre><code class="prism language-css"><span class="token selector">.App</span> <span class="token punctuation">{</span> <span class="token property">display</span><span class="token punctuation">:</span> -webkit-box<span class="token punctuation">;</span> <span class="token property">display</span><span class="token punctuation">:</span> -ms-flexbox<span class="token punctuation">;</span> <span class="token property">display</span><span class="token punctuation">:</span> flex<span class="token punctuation">;</span> <span class="token property">-webkit-box-orient</span><span class="token punctuation">:</span> horizontal<span class="token punctuation">;</span> <span class="token property">-webkit-box-direction</span><span class="token punctuation">:</span> normal<span class="token punctuation">;</span> <span class="token property">-ms-flex-direction</span><span class="token punctuation">:</span> row<span class="token punctuation">;</span> <span class="token property">flex-direction</span><span class="token punctuation">:</span> row<span class="token punctuation">;</span> <span class="token property">-webkit-box-align</span><span class="token punctuation">:</span> center<span class="token punctuation">;</span> <span class="token property">-ms-flex-align</span><span class="token punctuation">:</span> center<span class="token punctuation">;</span> <span class="token property">align-items</span><span class="token punctuation">:</span> center<span class="token punctuation">;</span> <span class="token punctuation">}</span> </code></pre> <p>If you need to disable autoprefixing for some reason, follow this section.</p> <p>CSS Grid Layout prefixing is disabled by default, but it will <strong>not</strong> strip manual prefixing.<br> If you’d like to opt-in to CSS Grid prefixing, first familiarize yourself about its limitations.<br><br> To enable CSS Grid prefixing, add <code>/* autoprefixer grid: on */</code> to the top of your CSS file.</p> <h3>Adding Images, Fonts, and Files</h3> <p>With Webpack, using static assets like images and fonts works similarly to CSS.</p> <p>You can <strong><code>import</code> a file right in a JavaScript module</strong>. This tells Webpack to include that file in the bundle. Unlike CSS imports, importing a file gives you a string value. This value is the final path you can reference in your code, e.g. as the <code>src</code> attribute of an image or the <code>href</code> of a link to a PDF.</p> <p>To reduce the number of requests to the server, importing images that are less than 10,000 bytes returns a data URI instead of a path. This applies to the following file extensions: bmp, gif, jpg, jpeg, and png. SVG files are excluded due to #1153.</p> <p>Here is an example:</p> <pre><code class="prism language-js"><span class="token keyword">import</span> React <span class="token keyword">from</span> <span class="token string">'react'</span><span class="token punctuation">;</span> <span class="token keyword">import</span> logo <span class="token keyword">from</span> <span class="token string">'./logo.png'</span><span class="token punctuation">;</span> <span class="token comment">// Tell Webpack this JS file uses this image</span> console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>logo<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">// /logo.84287d09.png</span> <span class="token keyword">function</span> <span class="token function">Header</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span> <span class="token comment">// Import result is the URL of your image</span> <span class="token keyword">return</span> <span class="token operator"><</span>img src<span class="token operator">=</span><span class="token punctuation">{</span>logo<span class="token punctuation">}</span> alt<span class="token operator">=</span><span class="token string">"Logo"</span> <span class="token operator">/</span><span class="token operator">></span><span class="token punctuation">;</span> <span class="token punctuation">}</span> <span class="token keyword">export</span> <span class="token keyword">default</span> Header<span class="token punctuation">;</span> </code></pre> <p>This ensures that when the project is built, Webpack will correctly move the images into the build folder, and provide us with correct paths.</p> <p>This works in CSS too:</p> <pre><code class="prism language-css"><span class="token selector">.Logo</span> <span class="token punctuation">{</span> <span class="token property">background-image</span><span class="token punctuation">:</span> <span class="token url">url(./logo.png)</span><span class="token punctuation">;</span> <span class="token punctuation">}</span> </code></pre> <p>Webpack finds all relative module references in CSS (they start with <code>./</code>) and replaces them with the final paths from the compiled bundle. If you make a typo or accidentally delete an important file, you will see a compilation error, just like when you import a non-existent JavaScript module. The final filenames in the compiled bundle are generated by Webpack from content hashes. If the file content changes in the future, Webpack will give it a different name in production so you don’t need to worry about long-term caching of assets.</p> <p>Please be advised that this is also a custom feature of Webpack.</p> <p><strong>It is not required for React</strong> but many people enjoy it (and React Native uses a similar mechanism for images).<br><br> An alternative way of handling static assets is described in the next section.</p> <h4>Adding SVGs</h4> <blockquote> <p>Note: this feature is available with <code>react-scripts@2.0.0</code> and higher.</p> </blockquote> <p>One way to add SVG files was described in the section above. You can also import SVGs directly as React components. You can use either of the two approaches. In your code it would look like this:</p> <pre><code class="prism language-js"><span class="token keyword">import</span> <span class="token punctuation">{</span> ReactComponent <span class="token keyword">as</span> Logo <span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">'./logo.svg'</span><span class="token punctuation">;</span> <span class="token keyword">const</span> <span class="token function-variable function">App</span> <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">(</span> <span class="token operator"><</span>div<span class="token operator">></span> <span class="token punctuation">{</span><span class="token comment">/* Logo is an actual React component */</span><span class="token punctuation">}</span> <span class="token operator"><</span>Logo <span class="token operator">/</span><span class="token operator">></span> <span class="token operator"><</span><span class="token operator">/</span>div<span class="token operator">></span> <span class="token punctuation">)</span><span class="token punctuation">;</span> </code></pre> <p>This is handy if you don’t want to load SVG as a separate file. Don’t forget the curly braces in the import! The <code>ReactComponent</code> import name is special and tells Create React App that you want a React component that renders an SVG, rather than its filename.</p> <h3>Using the <code>public</code> Folder</h3> <blockquote> <p>Note: this feature is available with <code>react-scripts@0.5.0</code> and higher.</p> </blockquote> <h4>Changing the HTML</h4> <p>The <code>public</code> folder contains the HTML file so you can tweak it, for example, to set the page title.<br> The <code><script></code> tag with the compiled code will be added to it automatically during the build process.</p> <h4>Adding Assets Outside of the Module System</h4> <p>You can also add other assets to the <code>public</code> folder.</p> <p>Note that we normally encourage you to <code>import</code> assets in JavaScript files instead.<br> For example, see the sections on adding a stylesheet and adding images and fonts.<br> This mechanism provides a number of benefits:</p> <ul> <li>Scripts and stylesheets get minified and bundled together to avoid extra network requests.</li> <li>Missing files cause compilation errors instead of 404 errors for your users.</li> <li>Result filenames include content hashes so you don’t need to worry about browsers caching their old versions.</li> </ul> <p>However there is an <strong>escape hatch</strong> that you can use to add an asset outside of the module system.</p> <p>If you put a file into the <code>public</code> folder, it will <strong>not</strong> be processed by Webpack. Instead it will be copied into the build folder untouched. To reference assets in the <code>public</code> folder, you need to use a special variable called <code>PUBLIC_URL</code>.</p> <p>Inside <code>index.html</code>, you can use it like this:</p> <pre><code class="prism language-html"><span class="token tag"><span class="token tag"><span class="token punctuation"><</span>link</span> <span class="token attr-name">rel</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>shortcut icon<span class="token punctuation">"</span></span> <span class="token attr-name">href</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>%PUBLIC_URL%/favicon.ico<span class="token punctuation">"</span></span><span class="token punctuation">></span></span> </code></pre> <p>Only files inside the <code>public</code> folder will be accessible by <code>%PUBLIC_URL%</code> prefix. If you need to use a file from <code>src</code> or <code>node_modules</code>, you’ll have to copy it there to explicitly specify your intention to make this file a part of the build.</p> <p>When you run <code>npm run build</code>, Create React App will substitute <code>%PUBLIC_URL%</code> with a correct absolute path so your project works even if you use client-side routing or host it at a non-root URL.</p> <p>In JavaScript code, you can use <code>process.env.PUBLIC_URL</code> for similar purposes:</p> <pre><code class="prism language-js"><span class="token function">render</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span> <span class="token comment">// Note: this is an escape hatch and should be used sparingly!</span> <span class="token comment">// Normally we recommend using `import` for getting asset URLs</span> <span class="token comment">// as described in “Adding Images and Fonts” above this section.</span> <span class="token keyword">return</span> <span class="token operator"><</span>img src<span class="token operator">=</span><span class="token punctuation">{</span>process<span class="token punctuation">.</span>env<span class="token punctuation">.</span><span class="token constant">PUBLIC_URL</span> <span class="token operator">+</span> <span class="token string">'/img/logo.png'</span><span class="token punctuation">}</span> <span class="token operator">/</span><span class="token operator">></span><span class="token punctuation">;</span> <span class="token punctuation">}</span> </code></pre> <p>Keep in mind the downsides of this approach:</p> <ul> <li>None of the files in <code>public</code> folder get post-processed or minified.</li> <li>Missing files will not be called at compilation time, and will cause 404 errors for your users.</li> <li>Result filenames won’t include content hashes so you’ll need to add query arguments or rename them every time they change.</li> </ul> <h4>When to Use the <code>public</code> Folder</h4> <p>Normally we recommend importing stylesheets, images, and fonts from JavaScript.<br> The <code>public</code> folder is useful as a workaround for a number of less common cases:</p> <ul> <li>You need a file with a specific name in the build output, such as <code>manifest.webmanifest</code>.</li> <li>You have thousands of images and need to dynamically reference their paths.</li> <li>You want to include a small script like <code>pace.js</code> outside of the bundled code.</li> <li>Some library may be incompatible with Webpack and you have no other option but to include it as a <code><script></code> tag.</li> </ul> <p>Note that if you add a <code><script></code> that declares global variables, you also need to read the next section on using them.</p> <h3>Using Global Variables</h3> <p>When you include a script in the HTML file that defines global variables and try to use one of these variables in the code, the linter will complain because it cannot see the definition of the variable.</p> <p>You can avoid this by reading the global variable explicitly from the <code>window</code> object, for example:</p> <pre><code class="prism language-js"><span class="token keyword">const</span> $ <span class="token operator">=</span> window<span class="token punctuation">.</span>$<span class="token punctuation">;</span> </code></pre> <p>This makes it obvious you are using a global variable intentionally rather than because of a typo.</p> <p>Alternatively, you can force the linter to ignore any line by adding <code>// eslint-disable-line</code> after it.</p> <h3>Adding Bootstrap</h3> <p>You don’t have to use reactstrap together with React but it is a popular library for integrating Bootstrap with React apps. If you need it, you can integrate it with Create React App by following these steps:</p> <p>Install reactstrap and Bootstrap from npm. reactstrap does not include Bootstrap CSS so this needs to be installed as well:</p> <pre><code class="prism language-sh">npm install --save reactstrap bootstrap@4 </code></pre> <p>Alternatively you may use <code>yarn</code>:</p> <pre><code class="prism language-sh">yarn add bootstrap@4 reactstrap </code></pre> <p>Import Bootstrap CSS and optionally Bootstrap theme CSS in the beginning of your <code>src/index.js</code> file:</p> <pre><code class="prism language-js"><span class="token keyword">import</span> <span class="token string">'bootstrap/dist/css/bootstrap.css'</span><span class="token punctuation">;</span> <span class="token comment">// Put any other imports below so that CSS from your</span> <span class="token comment">// components takes precedence over default styles.</span> </code></pre> <p>Import required reactstrap components within <code>src/App.js</code> file or your custom component files:</p> <pre><code class="prism language-js"><span class="token keyword">import</span> <span class="token punctuation">{</span> Button <span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">'reactstrap'</span><span class="token punctuation">;</span> </code></pre> <p>Now you are ready to use the imported reactstrap components within your component hierarchy defined in the render method. Here is an example <code>App.js</code> redone using reactstrap.</p> <h4>Using a Custom Theme</h4> <blockquote> <p>Note: this feature is available with <code>react-scripts@2.0.0</code> and higher.</p> </blockquote> <p>Sometimes you might need to tweak the visual styles of Bootstrap (or equivalent package).<br><br> As of <code>react-scripts@2.0.0</code> you can import <code>.scss</code> files. This makes it possible to use a package’s built-in Sass variables for global style preferences.</p> <p>To customize Bootstrap, create a file called <code>src/custom.scss</code> (or similar) and import the Bootstrap source stylesheet. Add any overrides <em>before</em> the imported file(s). You can reference Bootstrap’s documentation for the names of the available variables.</p> <pre><code class="prism language-scss">// Override default variables before the import $body-bg: #000; // Import Bootstrap and its default variables @import '~bootstrap/scss/bootstrap.scss'; </code></pre> <blockquote> <p><strong>Note:</strong> You must prefix imports from <code>node_modules</code> with <code>~</code> as displayed above.</p> </blockquote> <p>Finally, import the newly created <code>.scss</code> file instead of the default Bootstrap <code>.css</code> in the beginning of your <code>src/index.js</code> file, for example:</p> <pre><code class="prism language-javascript"><span class="token keyword">import</span> <span class="token string">'./custom.scss'</span><span class="token punctuation">;</span> </code></pre> <h3>Adding Flow</h3> <p>Flow is a static type checker that helps you write code with fewer bugs. Check out this introduction to using static types in JavaScript if you are new to this concept.</p> <p>Recent versions of Flow work with Create React App projects out of the box.</p> <p>To add Flow to a Create React App project, follow these steps:</p> <ol> <li>Run <code>npm install --save flow-bin</code> (or <code>yarn add flow-bin</code>).</li> <li>Add <code>"flow": "flow"</code> to the <code>scripts</code> section of your <code>package.json</code>.</li> <li>Run <code>npm run flow init</code> (or <code>yarn flow init</code>) to create a <code>.flowconfig</code> file in the root directory.</li> <li>Add <code>// @flow</code> to any files you want to type check (for example, to <code>src/App.js</code>).</li> </ol> <p>Now you can run <code>npm run flow</code> (or <code>yarn flow</code>) to check the files for type errors.<br> You can optionally use an IDE like Nuclide for a better integrated experience.<br> In the future we plan to integrate it into Create React App even more closely.</p> <p>To learn more about Flow, check out its documentation.</p> <h3>Adding Relay</h3> <p>Relay is a framework for building data-driven React applications powered by GraphQL. The current release candidate of Relay works with Create React App projects out of the box using Babel Macros. Simply set up your project as laid out in the Relay documentation, then make sure you have a version of the babel plugin providing the macro.</p> <p>To add it, run:</p> <pre><code class="prism language-sh">npm install --save --dev babel-plugin-relay@dev </code></pre> <p>Alternatively you may use <code>yarn</code>:</p> <pre><code class="prism language-sh">yarn upgrade babel-plugin-relay@dev </code></pre> <p>Then, wherever you use the <code>graphql</code> template tag, import the macro:</p> <pre><code class="prism language-js"><span class="token keyword">import</span> graphql <span class="token keyword">from</span> <span class="token string">'babel-plugin-relay/macro'</span><span class="token punctuation">;</span> <span class="token comment">// instead of:</span> <span class="token comment">// import { graphql } from "babel-plugin-relay"</span> graphql<span class="token template-string"><span class="token string">` query UserQuery { viewer { id } } `</span></span><span class="token punctuation">;</span> </code></pre> <p>To learn more about Relay, check out its documentation.</p> <h3>Adding a Router</h3> <p>Create React App doesn’t prescribe a specific routing solution, but React Router is the most popular one.</p> <p>To add it, run:</p> <pre><code class="prism language-sh">npm install --save react-router-dom </code></pre> <p>Alternatively you may use <code>yarn</code>:</p> <pre><code class="prism language-sh">yarn add react-router-dom </code></pre> <p>To try it, delete all the code in <code>src/App.js</code> and replace it with any of the examples on its website. The Basic Example is a good place to get started.</p> <p>Note that you may need to configure your production server to support client-side routing before deploying your app.</p> <h3>Adding Custom Environment Variables</h3> <blockquote> <p>Note: this feature is available with <code>react-scripts@0.2.3</code> and higher.</p> </blockquote> <p>Your project can consume variables declared in your environment as if they were declared locally in your JS files. By<br> default you will have <code>NODE_ENV</code> defined for you, and any other environment variables starting with<br> <code>REACT_APP_</code>.</p> <p><strong>The environment variables are embedded during the build time</strong>. Since Create React App produces a static HTML/CSS/JS bundle, it can’t possibly read them at runtime. To read them at runtime, you would need to load HTML into memory on the server and replace placeholders in runtime, just like described here. Alternatively you can rebuild the app on the server anytime you change them.</p> <blockquote> <p>Note: You must create custom environment variables beginning with <code>REACT_APP_</code>. Any other variables except <code>NODE_ENV</code> will be ignored to avoid accidentally exposing a private key on the machine that could have the same name. Changing any environment variables will require you to restart the development server if it is running.</p> </blockquote> <p>These environment variables will be defined for you on <code>process.env</code>. For example, having an environment<br> variable named <code>REACT_APP_SECRET_CODE</code> will be exposed in your JS as <code>process.env.REACT_APP_SECRET_CODE</code>.</p> <p>There is also a special built-in environment variable called <code>NODE_ENV</code>. You can read it from <code>process.env.NODE_ENV</code>. When you run <code>npm start</code>, it is always equal to <code>'development'</code>, when you run <code>npm test</code> it is always equal to <code>'test'</code>, and when you run <code>npm run build</code> to make a production bundle, it is always equal to <code>'production'</code>. <strong>You cannot override <code>NODE_ENV</code> manually.</strong> This prevents developers from accidentally deploying a slow development build to production.</p> <p>These environment variables can be useful for displaying information conditionally based on where the project is<br> deployed or consuming sensitive data that lives outside of version control.</p> <p>First, you need to have environment variables defined. For example, let’s say you wanted to consume a secret defined<br> in the environment inside a <code><form></code>:</p> <pre><code class="prism language-jsx">render() { return ( <div> <small>You are running this application in <b>{process.env.NODE_ENV}</b> mode.</small> <form> <input type="hidden" defaultValue={process.env.REACT_APP_SECRET_CODE} /> </form> </div> ); } </code></pre> <p>During the build, <code>process.env.REACT_APP_SECRET_CODE</code> will be replaced with the current value of the <code>REACT_APP_SECRET_CODE</code> environment variable. Remember that the <code>NODE_ENV</code> variable will be set for you automatically.</p> <p>When you load the app in the browser and inspect the <code><input></code>, you will see its value set to <code>abcdef</code>, and the bold text will show the environment provided when using <code>npm start</code>:</p> <pre><code class="prism language-html"><span class="token tag"><span class="token tag"><span class="token punctuation"><</span>div</span><span class="token punctuation">></span></span> <span class="token tag"><span class="token tag"><span class="token punctuation"><</span>small</span><span class="token punctuation">></span></span>You are running this application in <span class="token tag"><span class="token tag"><span class="token punctuation"><</span>b</span><span class="token punctuation">></span></span>development<span class="token tag"><span class="token tag"><span class="token punctuation"></</span>b</span><span class="token punctuation">></span></span> mode.<span class="token tag"><span class="token tag"><span class="token punctuation"></</span>small</span><span class="token punctuation">></span></span> <span class="token tag"><span class="token tag"><span class="token punctuation"><</span>form</span><span class="token punctuation">></span></span> <span class="token tag"><span class="token tag"><span class="token punctuation"><</span>input</span> <span class="token attr-name">type</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>hidden<span class="token punctuation">"</span></span> <span class="token attr-name">value</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>abcdef<span class="token punctuation">"</span></span> <span class="token punctuation">/></span></span> <span class="token tag"><span class="token tag"><span class="token punctuation"></</span>form</span><span class="token punctuation">></span></span> <span class="token tag"><span class="token tag"><span class="token punctuation"></</span>div</span><span class="token punctuation">></span></span> </code></pre> <p>The above form is looking for a variable called <code>REACT_APP_SECRET_CODE</code> from the environment. In order to consume this<br> value, we need to have it defined in the environment. This can be done using two ways: either in your shell or in<br> a <code>.env</code> file. Both of these ways are described in the next few sections.</p> <p>Having access to the <code>NODE_ENV</code> is also useful for performing actions conditionally:</p> <pre><code class="prism language-js"><span class="token keyword">if</span> <span class="token punctuation">(</span>process<span class="token punctuation">.</span>env<span class="token punctuation">.</span><span class="token constant">NODE_ENV</span> <span class="token operator">!==</span> <span class="token string">'production'</span><span class="token punctuation">)</span> <span class="token punctuation">{</span> analytics<span class="token punctuation">.</span><span class="token function">disable</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">}</span> </code></pre> <p>When you compile the app with <code>npm run build</code>, the minification step will strip out this condition, and the resulting bundle will be smaller.</p> <h4>Referencing Environment Variables in the HTML</h4> <blockquote> <p>Note: this feature is available with <code>react-scripts@0.9.0</code> and higher.</p> </blockquote> <p>You can also access the environment variables starting with <code>REACT_APP_</code> in the <code>public/index.html</code>. For example:</p> <pre><code class="prism language-html"><span class="token tag"><span class="token tag"><span class="token punctuation"><</span>title</span><span class="token punctuation">></span></span>%REACT_APP_WEBSITE_NAME%<span class="token tag"><span class="token tag"><span class="token punctuation"></</span>title</span><span class="token punctuation">></span></span> </code></pre> <p>Note that the caveats from the above section apply:</p> <ul> <li>Apart from a few built-in variables (<code>NODE_ENV</code> and <code>PUBLIC_URL</code>), variable names must start with <code>REACT_APP_</code> to work.</li> <li>The environment variables are injected at build time. If you need to inject them at runtime, follow this approach instead.</li> </ul> <h4>Adding Temporary Environment Variables In Your Shell</h4> <p>Defining environment variables can vary between OSes. It’s also important to know that this manner is temporary for the<br> life of the shell session.</p> <h5>Windows (cmd.exe)</h5> <pre><code class="prism language-cmd">set "REACT_APP_SECRET_CODE=abcdef" && npm start </code></pre> <p>(Note: Quotes around the variable assignment are required to avoid a trailing whitespace.)</p> <h5>Windows (Powershell)</h5> <pre><code class="prism language-Powershell">($env:REACT_APP_SECRET_CODE = "abcdef") -and (npm start) </code></pre> <h5>Linux, macOS (Bash)</h5> <pre><code class="prism language-bash">REACT_APP_SECRET_CODE<span class="token operator">=</span>abcdef <span class="token function">npm</span> start </code></pre> <h4>Adding Development Environment Variables In <code>.env</code></h4> <blockquote> <p>Note: this feature is available with <code>react-scripts@0.5.0</code> and higher.</p> </blockquote> <p>To define permanent environment variables, create a file called <code>.env</code> in the root of your project:</p> <pre><code>REACT_APP_SECRET_CODE=abcdef </code></pre> <blockquote> <p>Note: You must create custom environment variables beginning with <code>REACT_APP_</code>. Any other variables except <code>NODE_ENV</code> will be ignored to avoid accidentally exposing a private key on the machine that could have the same name. Changing any environment variables will require you to restart the development server if it is running.</p> </blockquote> <p><code>.env</code> files <strong>should be</strong> checked into source control (with the exclusion of <code>.env*.local</code>).</p> <h5>What other <code>.env</code> files can be used?</h5> <blockquote> <p>Note: this feature is <strong>available with <code>react-scripts@1.0.0</code> and higher</strong>.</p> </blockquote> <ul> <li><code>.env</code>: Default.</li> <li><code>.env.local</code>: Local overrides. <strong>This file is loaded for all environments except test.</strong></li> <li><code>.env.development</code>, <code>.env.test</code>, <code>.env.production</code>: Environment-specific settings.</li> <li><code>.env.development.local</code>, <code>.env.test.local</code>, <code>.env.production.local</code>: Local overrides of environment-specific settings.</li> </ul> <p>Files on the left have more priority than files on the right:</p> <ul> <li><code>npm start</code>: <code>.env.development.local</code>, <code>.env.development</code>, <code>.env.local</code>, <code>.env</code></li> <li><code>npm run build</code>: <code>.env.production.local</code>, <code>.env.production</code>, <code>.env.local</code>, <code>.env</code></li> <li><code>npm test</code>: <code>.env.test.local</code>, <code>.env.test</code>, <code>.env</code> (note <code>.env.local</code> is missing)</li> </ul> <p>These variables will act as the defaults if the machine does not explicitly set them.<br><br> Please refer to the dotenv documentation for more details.</p> <blockquote> <p>Note: If you are defining environment variables for development, your CI and/or hosting platform will most likely need<br> these defined as well. Consult their documentation how to do this. For example, see the documentation for Travis CI or Heroku.</p> </blockquote> <h5>Expanding Environment Variables In <code>.env</code></h5> <blockquote> <p>Note: this feature is available with <code>react-scripts@1.1.0</code> and higher.</p> </blockquote> <p>Expand variables already on your machine for use in your <code>.env</code> file (using dotenv-expand).</p> <p>For example, to get the environment variable <code>npm_package_version</code>:</p> <pre><code>REACT_APP_VERSION=$npm_package_version # also works: # REACT_APP_VERSION=${npm_package_version} </code></pre> <p>Or expand variables local to the current <code>.env</code> file:</p> <pre><code>DOMAIN=www.example.com REACT_APP_FOO=$DOMAIN/foo REACT_APP_BAR=$DOMAIN/bar </code></pre> <h3>Can I Use Decorators?</h3> <p>Some popular libraries use decorators in their documentation.<br><br> Create React App intentionally doesn’t support decorator syntax at the moment because:</p> <ul> <li>It is an experimental proposal and is subject to change (in fact, it has already changed once, and will change again).</li> <li>Most libraries currently support only the old version of the proposal — which will never be a standard.</li> </ul> <p>However in many cases you can rewrite decorator-based code without decorators just as fine.<br><br> Please refer to these two threads for reference:</p> <ul> <li>#214</li> <li>#411</li> </ul> <p>Create React App will add decorator support when the specification advances to a stable stage.</p> <h3>Fetching Data with AJAX Requests</h3> <p>React doesn’t prescribe a specific approach to data fetching, but people commonly use either a library like axios or the <code>fetch()</code> API provided by the browser.</p> <p>The global <code>fetch</code> function allows you to easily make AJAX requests. It takes in a URL as an input and returns a <code>Promise</code> that resolves to a <code>Response</code> object. You can find more information about <code>fetch</code> here.</p> <p>A Promise represents the eventual result of an asynchronous operation, you can find more information about Promises here and here. Both axios and <code>fetch()</code> use Promises under the hood. You can also use the <code>async / await</code> syntax to reduce the callback nesting.</p> <p>Make sure the <code>fetch()</code> API and Promises are available in your target audience’s browsers.<br> For example, support in Internet Explorer requires a polyfill.</p> <p>You can learn more about making AJAX requests from React components in the FAQ entry on the React website.</p> <h3>Integrating with an API Backend</h3> <p>These tutorials will help you to integrate your app with an API backend running on another port,<br> using <code>fetch()</code> to access it.</p> <h4>Node</h4> <p>Check out this tutorial.<br> You can find the companion GitHub repository here.</p> <h4>Ruby on Rails</h4> <p>Check out this tutorial.<br> You can find the companion GitHub repository here.</p> <h4>API Platform (PHP and Symfony)</h4> <p>API Platform is a framework designed to build API-driven projects.<br> It allows to create hypermedia and GraphQL APIs in minutes.<br> It is shipped with an official Progressive Web App generator as well as a dynamic administration interface, both built for Create React App.<br> Check out this tutorial.</p> <h3>Proxying API Requests in Development</h3> <blockquote> <p>Note: this feature is available with <code>react-scripts@0.2.3</code> and higher.</p> </blockquote> <p>People often serve the front-end React app from the same host and port as their backend implementation.<br><br> For example, a production setup might look like this after the app is deployed:</p> <pre><code>/ - static server returns index.html with React app /todos - static server returns index.html with React app /api/todos - server handles any /api/* requests using the backend implementation </code></pre> <p>Such setup is <strong>not</strong> required. However, if you <strong>do</strong> have a setup like this, it is convenient to write requests like <code>fetch('/api/todos')</code> without worrying about redirecting them to another host or port during development.</p> <p>To tell the development server to proxy any unknown requests to your API server in development, add a <code>proxy</code> field to your <code>package.json</code>, for example:</p> <pre><code class="prism language-js"> <span class="token string">"proxy"</span><span class="token punctuation">:</span> <span class="token string">"http://localhost:4000"</span><span class="token punctuation">,</span> </code></pre> <p>This way, when you <code>fetch('/api/todos')</code> in development, the development server will recognize that it’s not a static asset, and will proxy your request to <code>http://localhost:4000/api/todos</code> as a fallback. The development server will <strong>only</strong> attempt to send requests without <code>text/html</code> in its <code>Accept</code> header to the proxy.</p> <p>Conveniently, this avoids CORS issues and error messages like this in development:</p> <pre><code>Fetch API cannot load http://localhost:4000/api/todos. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. </code></pre> <p>Keep in mind that <code>proxy</code> only has effect in development (with <code>npm start</code>), and it is up to you to ensure that URLs like <code>/api/todos</code> point to the right thing in production. You don’t have to use the <code>/api</code> prefix. Any unrecognized request without a <code>text/html</code> accept header will be redirected to the specified <code>proxy</code>.</p> <p>The <code>proxy</code> option supports HTTP, HTTPS and WebSocket connections.<br><br> If the <code>proxy</code> option is <strong>not</strong> flexible enough for you, alternatively you can:</p> <ul> <li>Configure the proxy yourself</li> <li>Enable CORS on your server (here’s how to do it for Express).</li> <li>Use environment variables to inject the right server host and port into your app.</li> </ul> <h4>“Invalid Host Header” Errors After Configuring Proxy</h4> <p>When you enable the <code>proxy</code> option, you opt into a more strict set of host checks. This is necessary because leaving the backend open to remote hosts makes your computer vulnerable to DNS rebinding attacks. The issue is explained in this article and this issue.</p> <p>This shouldn’t affect you when developing on <code>localhost</code>, but if you develop remotely like described here, you will see this error in the browser after enabling the <code>proxy</code> option:</p> <blockquote> <p>Invalid Host header</p> </blockquote> <p>To work around it, you can specify your public development host in a file called <code>.env.development</code> in the root of your project:</p> <pre><code>HOST=mypublicdevhost.com </code></pre> <p>If you restart the development server now and load the app from the specified host, it should work.</p> <p>If you are still having issues or if you’re using a more exotic environment like a cloud editor, you can bypass the host check completely by adding a line to <code>.env.development.local</code>. <strong>Note that this is dangerous and exposes your machine to remote code execution from malicious websites:</strong></p> <pre><code># NOTE: THIS IS DANGEROUS! # It exposes your machine to attacks from the websites you visit. DANGEROUSLY_DISABLE_HOST_CHECK=true </code></pre> <p>We don’t recommend this approach.</p> <h4>Configuring the Proxy Manually</h4> <blockquote> <p>Note: this feature is available with <code>react-scripts@2.0.0</code> and higher.</p> </blockquote> <p>If the <code>proxy</code> option is <strong>not</strong> flexible enough for you, you can get direct access to the Express app instance and hook up your own proxy middleware.</p> <p>You can use this feature in conjunction with the <code>proxy</code> property in <code>package.json</code>, but it is recommended you consolidate all of your logic into <code>src/setupProxy.js</code>.</p> <p>First, install <code>http-proxy-middleware</code> using npm or Yarn:</p> <pre><code class="prism language-bash">$ <span class="token function">npm</span> <span class="token function">install</span> http-proxy-middleware --save $ <span class="token comment"># or</span> $ yarn add http-proxy-middleware </code></pre> <p>Next, create <code>src/setupProxy.js</code> and place the following contents in it:</p> <pre><code class="prism language-js"><span class="token keyword">const</span> proxy <span class="token operator">=</span> <span class="token function">require</span><span class="token punctuation">(</span><span class="token string">'http-proxy-middleware'</span><span class="token punctuation">)</span><span class="token punctuation">;</span> module<span class="token punctuation">.</span><span class="token function-variable function">exports</span> <span class="token operator">=</span> <span class="token keyword">function</span><span class="token punctuation">(</span>app<span class="token punctuation">)</span> <span class="token punctuation">{</span> <span class="token comment">// ...</span> <span class="token punctuation">}</span><span class="token punctuation">;</span> </code></pre> <p>You can now register proxies as you wish! Here’s an example using the above <code>http-proxy-middleware</code>:</p> <pre><code class="prism language-js"><span class="token keyword">const</span> proxy <span class="token operator">=</span> <span class="token function">require</span><span class="token punctuation">(</span><span class="token string">'http-proxy-middleware'</span><span class="token punctuation">)</span><span class="token punctuation">;</span> module<span class="token punctuation">.</span><span class="token function-variable function">exports</span> <span class="token operator">=</span> <span class="token keyword">function</span><span class="token punctuation">(</span>app<span class="token punctuation">)</span> <span class="token punctuation">{</span> app<span class="token punctuation">.</span><span class="token function">use</span><span class="token punctuation">(</span><span class="token function">proxy</span><span class="token punctuation">(</span><span class="token string">'/api'</span><span class="token punctuation">,</span> <span class="token punctuation">{</span> target<span class="token punctuation">:</span> <span class="token string">'http://localhost:5000/'</span> <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">}</span><span class="token punctuation">;</span> </code></pre> <blockquote> <p><strong>Note:</strong> You do not need to import this file anywhere. It is automatically registered when you start the development server.</p> </blockquote> <blockquote> <p><strong>Note:</strong> This file only supports Node’s JavaScript syntax. Be sure to only use supported language features (i.e. no support for Flow, ES Modules, etc).</p> </blockquote> <blockquote> <p><strong>Note:</strong> Passing the path to the proxy function allows you to use globbing and/or pattern matching on the path, which is more flexible than the express route matching.</p> </blockquote> <h3>Using HTTPS in Development</h3> <blockquote> <p>Note: this feature is available with <code>react-scripts@0.4.0</code> and higher.</p> </blockquote> <p>You may require the dev server to serve pages over HTTPS. One particular case where this could be useful is when using the “proxy” feature to proxy requests to an API server when that API server is itself serving HTTPS.</p> <p>To do this, set the <code>HTTPS</code> environment variable to <code>true</code>, then start the dev server as usual with <code>npm start</code>:</p> <h5>Windows (cmd.exe)</h5> <pre><code class="prism language-cmd">set HTTPS=true&&npm start </code></pre> <p>(Note: the lack of whitespace is intentional.)</p> <h5>Windows (Powershell)</h5> <pre><code class="prism language-Powershell">($env:HTTPS = "true") -and (npm start) </code></pre> <h5>Linux, macOS (Bash)</h5> <pre><code class="prism language-bash">HTTPS<span class="token operator">=</span>true <span class="token function">npm</span> start </code></pre> <p>Note that the server will use a self-signed certificate, so your web browser will almost definitely display a warning upon accessing the page.</p> <h3>Generating Dynamic <code><meta></code> Tags on the Server</h3> <p>Since Create React App doesn’t support server rendering, you might be wondering how to make <code><meta></code> tags dynamic and reflect the current URL. To solve this, we recommend to add placeholders into the HTML, like this:</p> <pre><code class="prism language-html"><span class="token doctype"><!doctype html></span> <span class="token tag"><span class="token tag"><span class="token punctuation"><</span>html</span> <span class="token attr-name">lang</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>en<span class="token punctuation">"</span></span><span class="token punctuation">></span></span> <span class="token tag"><span class="token tag"><span class="token punctuation"><</span>head</span><span class="token punctuation">></span></span> <span class="token tag"><span class="token tag"><span class="token punctuation"><</span>meta</span> <span class="token attr-name">property</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>og:title<span class="token punctuation">"</span></span> <span class="token attr-name">content</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>__OG_TITLE__<span class="token punctuation">"</span></span><span class="token punctuation">></span></span> <span class="token tag"><span class="token tag"><span class="token punctuation"><</span>meta</span> <span class="token attr-name">property</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>og:description<span class="token punctuation">"</span></span> <span class="token attr-name">content</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>__OG_DESCRIPTION__<span class="token punctuation">"</span></span><span class="token punctuation">></span></span> </code></pre> <p>Then, on the server, regardless of the backend you use, you can read <code>index.html</code> into memory and replace <code>__OG_TITLE__</code>, <code>__OG_DESCRIPTION__</code>, and any other placeholders with values depending on the current URL. Just make sure to sanitize and escape the interpolated values so that they are safe to embed into HTML!</p> <p>If you use a Node server, you can even share the route matching logic between the client and the server. However duplicating it also works fine in simple cases.</p> <h3>Pre-Rendering into Static HTML Files</h3> <p>If you’re hosting your <code>build</code> with a static hosting provider you can use react-snapshot or react-snap to generate HTML pages for each route, or relative link, in your application. These pages will then seamlessly become active, or “hydrated”, when the JavaScript bundle has loaded.</p> <p>There are also opportunities to use this outside of static hosting, to take the pressure off the server when generating and caching routes.</p> <p>The primary benefit of pre-rendering is that you get the core content of each page <em>with</em> the HTML payload—regardless of whether or not your JavaScript bundle successfully downloads. It also increases the likelihood that each route of your application will be picked up by search engines.</p> <p>You can read more about zero-configuration pre-rendering (also called snapshotting) here.</p> <h3>Injecting Data from the Server into the Page</h3> <p>Similarly to the previous section, you can leave some placeholders in the HTML that inject global variables, for example:</p> <pre><code class="prism language-js"><span class="token operator"><</span><span class="token operator">!</span>doctype html<span class="token operator">></span> <span class="token operator"><</span>html lang<span class="token operator">=</span><span class="token string">"en"</span><span class="token operator">></span> <span class="token operator"><</span>head<span class="token operator">></span> <span class="token operator"><</span>script<span class="token operator">></span> window<span class="token punctuation">.</span><span class="token constant">SERVER_DATA</span> <span class="token operator">=</span> __SERVER_DATA__<span class="token punctuation">;</span> <span class="token operator"><</span><span class="token operator">/</span>script<span class="token operator">></span> </code></pre> <p>Then, on the server, you can replace <code>__SERVER_DATA__</code> with a JSON of real data right before sending the response. The client code can then read <code>window.SERVER_DATA</code> to use it. <strong>Make sure to sanitize the JSON before sending it to the client as it makes your app vulnerable to XSS attacks.</strong></p> <h3>Running Tests</h3> <blockquote> <p>Note: this feature is available with <code>react-scripts@0.3.0</code> and higher.<br></p> </blockquote> <blockquote> <p>Read the migration guide to learn how to enable it in older projects!</p> </blockquote> <p>Create React App uses Jest as its test runner. To prepare for this integration, we did a major revamp of Jest so if you heard bad things about it years ago, give it another try.</p> <p>Jest is a Node-based runner. This means that the tests always run in a Node environment and not in a real browser. This lets us enable fast iteration speed and prevent flakiness.</p> <p>While Jest provides browser globals such as <code>window</code> thanks to jsdom, they are only approximations of the real browser behavior. Jest is intended to be used for unit tests of your logic and your components rather than the DOM quirks.</p> <p>We recommend that you use a separate tool for browser end-to-end tests if you need them. They are beyond the scope of Create React App.</p> <h4>Filename Conventions</h4> <p>Jest will look for test files with any of the following popular naming conventions:</p> <ul> <li>Files with <code>.js</code> suffix in <code>__tests__</code> folders.</li> <li>Files with <code>.test.js</code> suffix.</li> <li>Files with <code>.spec.js</code> suffix.</li> </ul> <p>The <code>.test.js</code> / <code>.spec.js</code> files (or the <code>__tests__</code> folders) can be located at any depth under the <code>src</code> top level folder.</p> <p>We recommend to put the test files (or <code>__tests__</code> folders) next to the code they are testing so that relative imports appear shorter. For example, if <code>App.test.js</code> and <code>App.js</code> are in the same folder, the test just needs to <code>import App from './App'</code> instead of a long relative path. Colocation also helps find tests more quickly in larger projects.</p> <h4>Command Line Interface</h4> <p>When you run <code>npm test</code>, Jest will launch in the watch mode. Every time you save a file, it will re-run the tests, just like <code>npm start</code> recompiles the code.</p> <p>The watcher includes an interactive command-line interface with the ability to run all tests, or focus on a search pattern. It is designed this way so that you can keep it open and enjoy fast re-runs. You can learn the commands from the “Watch Usage” note that the watcher prints after every run:</p> <p><img src="http://img.e-com-net.com/image/info8/cfaead4d466b456c8709969f86eaeebd.gif" alt="Jest watch mode" width="0" height="0"></p> <h4>Version Control Integration</h4> <p>By default, when you run <code>npm test</code>, Jest will only run the tests related to files changed since the last commit. This is an optimization designed to make your tests run fast regardless of how many tests you have. However it assumes that you don’t often commit the code that doesn’t pass the tests.</p> <p>Jest will always explicitly mention that it only ran tests related to the files changed since the last commit. You can also press <code>a</code> in the watch mode to force Jest to run all tests.</p> <p>Jest will always run all tests on a continuous integration server or if the project is not inside a Git or Mercurial repository.</p> <h4>Writing Tests</h4> <p>To create tests, add <code>it()</code> (or <code>test()</code>) blocks with the name of the test and its code. You may optionally wrap them in <code>describe()</code> blocks for logical grouping but this is neither required nor recommended.</p> <p>Jest provides a built-in <code>expect()</code> global function for making assertions. A basic test could look like this:</p> <pre><code class="prism language-js"><span class="token keyword">import</span> sum <span class="token keyword">from</span> <span class="token string">'./sum'</span><span class="token punctuation">;</span> <span class="token function">it</span><span class="token punctuation">(</span><span class="token string">'sums numbers'</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span> <span class="token function">expect</span><span class="token punctuation">(</span><span class="token function">sum</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toEqual</span><span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token function">expect</span><span class="token punctuation">(</span><span class="token function">sum</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toEqual</span><span class="token punctuation">(</span><span class="token number">4</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span> </code></pre> <p>All <code>expect()</code> matchers supported by Jest are extensively documented here.<br><br> You can also use <code>jest.fn()</code> and <code>expect(fn).toBeCalled()</code> to create “spies” or mock functions.</p> <h4>Testing Components</h4> <p>There is a broad spectrum of component testing techniques. They range from a “smoke test” verifying that a component renders without throwing, to shallow rendering and testing some of the output, to full rendering and testing component lifecycle and state changes.</p> <p>Different projects choose different testing tradeoffs based on how often components change, and how much logic they contain. If you haven’t decided on a testing strategy yet, we recommend that you start with creating simple smoke tests for your components:</p> <pre><code class="prism language-js"><span class="token keyword">import</span> React <span class="token keyword">from</span> <span class="token string">'react'</span><span class="token punctuation">;</span> <span class="token keyword">import</span> ReactDOM <span class="token keyword">from</span> <span class="token string">'react-dom'</span><span class="token punctuation">;</span> <span class="token keyword">import</span> App <span class="token keyword">from</span> <span class="token string">'./App'</span><span class="token punctuation">;</span> <span class="token function">it</span><span class="token punctuation">(</span><span class="token string">'renders without crashing'</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span> <span class="token keyword">const</span> div <span class="token operator">=</span> document<span class="token punctuation">.</span><span class="token function">createElement</span><span class="token punctuation">(</span><span class="token string">'div'</span><span class="token punctuation">)</span><span class="token punctuation">;</span> ReactDOM<span class="token punctuation">.</span><span class="token function">render</span><span class="token punctuation">(</span><span class="token operator"><</span>App <span class="token operator">/</span><span class="token operator">></span><span class="token punctuation">,</span> div<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span> </code></pre> <p>This test mounts a component and makes sure that it didn’t throw during rendering. Tests like this provide a lot of value with very little effort so they are great as a starting point, and this is the test you will find in <code>src/App.test.js</code>.</p> <p>When you encounter bugs caused by changing components, you will gain a deeper insight into which parts of them are worth testing in your application. This might be a good time to introduce more specific tests asserting specific expected output or behavior.</p> <p>If you’d like to test components in isolation from the child components they render, we recommend using <code>shallow()</code> rendering API from Enzyme. To install it, run:</p> <pre><code class="prism language-sh">npm install --save enzyme enzyme-adapter-react-16 react-test-renderer </code></pre> <p>Alternatively you may use <code>yarn</code>:</p> <pre><code class="prism language-sh">yarn add enzyme enzyme-adapter-react-16 react-test-renderer </code></pre> <p>As of Enzyme 3, you will need to install Enzyme along with an Adapter corresponding to the version of React you are using. (The examples above use the adapter for React 16.)</p> <p>The adapter will also need to be configured in your global setup file:</p> <h5><code>src/setupTests.js</code></h5> <pre><code class="prism language-js"><span class="token keyword">import</span> <span class="token punctuation">{</span> configure <span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">'enzyme'</span><span class="token punctuation">;</span> <span class="token keyword">import</span> Adapter <span class="token keyword">from</span> <span class="token string">'enzyme-adapter-react-16'</span><span class="token punctuation">;</span> <span class="token function">configure</span><span class="token punctuation">(</span><span class="token punctuation">{</span> adapter<span class="token punctuation">:</span> <span class="token keyword">new</span> <span class="token class-name">Adapter</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span> </code></pre> <blockquote> <p>Note: Keep in mind that if you decide to “eject” before creating <code>src/setupTests.js</code>, the resulting <code>package.json</code> file won’t contain any reference to it. Read here to learn how to add this after ejecting.</p> </blockquote> <p>Now you can write a smoke test with it:</p> <pre><code class="prism language-js"><span class="token keyword">import</span> React <span class="token keyword">from</span> <span class="token string">'react'</span><span class="token punctuation">;</span> <span class="token keyword">import</span> <span class="token punctuation">{</span> shallow <span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">'enzyme'</span><span class="token punctuation">;</span> <span class="token keyword">import</span> App <span class="token keyword">from</span> <span class="token string">'./App'</span><span class="token punctuation">;</span> <span class="token function">it</span><span class="token punctuation">(</span><span class="token string">'renders without crashing'</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span> <span class="token function">shallow</span><span class="token punctuation">(</span><span class="token operator"><</span>App <span class="token operator">/</span><span class="token operator">></span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span> </code></pre> <p>Unlike the previous smoke test using <code>ReactDOM.render()</code>, this test only renders <code><App></code> and doesn’t go deeper. For example, even if <code><App></code> itself renders a <code><Button></code> that throws, this test will pass. Shallow rendering is great for isolated unit tests, but you may still want to create some full rendering tests to ensure the components integrate correctly. Enzyme supports full rendering with <code>mount()</code>, and you can also use it for testing state changes and component lifecycle.</p> <p>You can read the Enzyme documentation for more testing techniques. Enzyme documentation uses Chai and Sinon for assertions but you don’t have to use them because Jest provides built-in <code>expect()</code> and <code>jest.fn()</code> for spies.</p> <p>Here is an example from Enzyme documentation that asserts specific output, rewritten to use Jest matchers:</p> <pre><code class="prism language-js"><span class="token keyword">import</span> React <span class="token keyword">from</span> <span class="token string">'react'</span><span class="token punctuation">;</span> <span class="token keyword">import</span> <span class="token punctuation">{</span> shallow <span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">'enzyme'</span><span class="token punctuation">;</span> <span class="token keyword">import</span> App <span class="token keyword">from</span> <span class="token string">'./App'</span><span class="token punctuation">;</span> <span class="token function">it</span><span class="token punctuation">(</span><span class="token string">'renders welcome message'</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span> <span class="token keyword">const</span> wrapper <span class="token operator">=</span> <span class="token function">shallow</span><span class="token punctuation">(</span><span class="token operator"><</span>App <span class="token operator">/</span><span class="token operator">></span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token keyword">const</span> welcome <span class="token operator">=</span> <span class="token operator"><</span>h2<span class="token operator">></span>Welcome to React<span class="token operator"><</span><span class="token operator">/</span>h2<span class="token operator">></span><span class="token punctuation">;</span> <span class="token comment">// expect(wrapper.contains(welcome)).toBe(true);</span> <span class="token function">expect</span><span class="token punctuation">(</span>wrapper<span class="token punctuation">.</span><span class="token function">contains</span><span class="token punctuation">(</span>welcome<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toEqual</span><span class="token punctuation">(</span><span class="token boolean">true</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span> </code></pre> <p>All Jest matchers are extensively documented here.<br><br> Nevertheless you can use a third-party assertion library like Chai if you want to, as described below.</p> <p>Additionally, you might find jest-enzyme helpful to simplify your tests with readable matchers. The above <code>contains</code> code can be written more simply with jest-enzyme.</p> <pre><code class="prism language-js"><span class="token function">expect</span><span class="token punctuation">(</span>wrapper<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toContainReact</span><span class="token punctuation">(</span>welcome<span class="token punctuation">)</span><span class="token punctuation">;</span> </code></pre> <p>To enable this, install <code>jest-enzyme</code>:</p> <pre><code class="prism language-sh">npm install --save jest-enzyme </code></pre> <p>Alternatively you may use <code>yarn</code>:</p> <pre><code class="prism language-sh">yarn add jest-enzyme </code></pre> <p>Import it in <code>src/setupTests.js</code> to make its matchers available in every test:</p> <pre><code class="prism language-js"><span class="token keyword">import</span> <span class="token string">'jest-enzyme'</span><span class="token punctuation">;</span> </code></pre> <h5>Use <code>react-testing-library</code></h5> <p>As an alternative or companion to <code>enzyme</code>, you may consider using <code>react-testing-library</code>. <code>react-testing-library</code> is a library for testing React components in a way that resembles the way the components are used by end users. It is well suited for unit, integration, and end-to-end testing of React components and applications. It works more directly with DOM nodes, and therefore it’s recommended to use with <code>jest-dom</code> for improved assertions.</p> <p>To install <code>react-testing-library</code> and <code>jest-dom</code>, you can run:</p> <pre><code class="prism language-sh">npm install --save react-testing-library jest-dom </code></pre> <p>Alternatively you may use <code>yarn</code>:</p> <pre><code class="prism language-sh">yarn add react-testing-library jest-dom </code></pre> <p>Similar to <code>enzyme</code> you can create a <code>src/setupTests.js</code> file to avoid boilerplate in your test files:</p> <pre><code class="prism language-js"><span class="token comment">// react-testing-library renders your components to document.body,</span> <span class="token comment">// this will ensure they're removed after each test.</span> <span class="token keyword">import</span> <span class="token string">'react-testing-library/cleanup-after-each'</span><span class="token punctuation">;</span> <span class="token comment">// this adds jest-dom's custom assertions</span> <span class="token keyword">import</span> <span class="token string">'jest-dom/extend-expect'</span><span class="token punctuation">;</span> </code></pre> <p>Here’s an example of using <code>react-testing-library</code> and <code>jest-dom</code> for testing that the <code><App /></code> component renders “Welcome to React”.</p> <pre><code class="prism language-js"><span class="token keyword">import</span> React <span class="token keyword">from</span> <span class="token string">'react'</span><span class="token punctuation">;</span> <span class="token keyword">import</span> <span class="token punctuation">{</span> render <span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">'react-testing-library'</span><span class="token punctuation">;</span> <span class="token keyword">import</span> App <span class="token keyword">from</span> <span class="token string">'./App'</span><span class="token punctuation">;</span> <span class="token function">it</span><span class="token punctuation">(</span><span class="token string">'renders welcome message'</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span> <span class="token keyword">const</span> <span class="token punctuation">{</span> getByText <span class="token punctuation">}</span> <span class="token operator">=</span> <span class="token function">render</span><span class="token punctuation">(</span><span class="token operator"><</span>App <span class="token operator">/</span><span class="token operator">></span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token function">expect</span><span class="token punctuation">(</span><span class="token function">getByText</span><span class="token punctuation">(</span><span class="token string">'Welcome to React'</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toBeInTheDocument</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span> </code></pre> <p>Learn more about the utilities provided by <code>react-testing-library</code> to facilitate testing asynchronous interactions as well as selecting form elements from the <code>react-testing-library</code> documentation and examples.</p> <h4>Using Third Party Assertion Libraries</h4> <p>We recommend that you use <code>expect()</code> for assertions and <code>jest.fn()</code> for spies. If you are having issues with them please file those against Jest, and we’ll fix them. We intend to keep making them better for React, supporting, for example, pretty-printing React elements as JSX.</p> <p>However, if you are used to other libraries, such as Chai and Sinon, or if you have existing code using them that you’d like to port over, you can import them normally like this:</p> <pre><code class="prism language-js"><span class="token keyword">import</span> sinon <span class="token keyword">from</span> <span class="token string">'sinon'</span><span class="token punctuation">;</span> <span class="token keyword">import</span> <span class="token punctuation">{</span> expect <span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">'chai'</span><span class="token punctuation">;</span> </code></pre> <p>and then use them in your tests like you normally do.</p> <h4>Initializing Test Environment</h4> <blockquote> <p>Note: this feature is available with <code>react-scripts@0.4.0</code> and higher.</p> </blockquote> <p>If your app uses a browser API that you need to mock in your tests or if you just need a global setup before running your tests, add a <code>src/setupTests.js</code> to your project. It will be automatically executed before running your tests.</p> <p>For example:</p> <h5><code>src/setupTests.js</code></h5> <pre><code class="prism language-js"><span class="token keyword">const</span> localStorageMock <span class="token operator">=</span> <span class="token punctuation">{</span> getItem<span class="token punctuation">:</span> jest<span class="token punctuation">.</span><span class="token function">fn</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> setItem<span class="token punctuation">:</span> jest<span class="token punctuation">.</span><span class="token function">fn</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> clear<span class="token punctuation">:</span> jest<span class="token punctuation">.</span><span class="token function">fn</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token punctuation">}</span><span class="token punctuation">;</span> global<span class="token punctuation">.</span>localStorage <span class="token operator">=</span> localStorageMock<span class="token punctuation">;</span> </code></pre> <blockquote> <p>Note: Keep in mind that if you decide to “eject” before creating <code>src/setupTests.js</code>, the resulting <code>package.json</code> file won’t contain any reference to it, so you should manually create the property <code>setupTestFrameworkScriptFile</code> in the configuration for Jest, something like the following:</p> </blockquote> <blockquote> <pre><code class="prism language-js"><span class="token string">"jest"</span><span class="token punctuation">:</span> <span class="token punctuation">{</span> <span class="token comment">// ...</span> <span class="token string">"setupTestFrameworkScriptFile"</span><span class="token punctuation">:</span> <span class="token string">"<rootDir>/src/setupTests.js"</span> <span class="token punctuation">}</span> </code></pre> </blockquote> <h4>Focusing and Excluding Tests</h4> <p>You can replace <code>it()</code> with <code>xit()</code> to temporarily exclude a test from being executed.<br><br> Similarly, <code>fit()</code> lets you focus on a specific test without running any other tests.</p> <h4>Coverage Reporting</h4> <p>Jest has an integrated coverage reporter that works well with ES6 and requires no configuration.<br><br> Run <code>npm test -- --coverage</code> (note extra <code>--</code> in the middle) to include a coverage report like this:</p> <p></p> <p>Note that tests run much slower with coverage so it is recommended to run it separately from your normal workflow.</p> <h5>Configuration</h5> <p>The default Jest coverage configuration can be overridden by adding any of the following supported keys to a Jest config in your package.json.</p> <p>Supported overrides:</p> <ul> <li><code>collectCoverageFrom</code></li> <li><code>coverageReporters</code></li> <li><code>coverageThreshold</code></li> <li><code>snapshotSerializers</code></li> </ul> <p>Example package.json:</p> <pre><code class="prism language-json"><span class="token punctuation">{</span> <span class="token string">"name"</span><span class="token punctuation">:</span> <span class="token string">"your-package"</span><span class="token punctuation">,</span> <span class="token string">"jest"</span><span class="token punctuation">:</span> <span class="token punctuation">{</span> <span class="token string">"collectCoverageFrom"</span><span class="token punctuation">:</span> <span class="token punctuation">[</span> <span class="token string">"src/**/*.{js,jsx}"</span><span class="token punctuation">,</span> <span class="token string">"!<rootDir>/node_modules/"</span><span class="token punctuation">,</span> <span class="token string">"!<rootDir>/path/to/dir/"</span> <span class="token punctuation">]</span><span class="token punctuation">,</span> <span class="token string">"coverageThreshold"</span><span class="token punctuation">:</span> <span class="token punctuation">{</span> <span class="token string">"global"</span><span class="token punctuation">:</span> <span class="token punctuation">{</span> <span class="token string">"branches"</span><span class="token punctuation">:</span> <span class="token number">90</span><span class="token punctuation">,</span> <span class="token string">"functions"</span><span class="token punctuation">:</span> <span class="token number">90</span><span class="token punctuation">,</span> <span class="token string">"lines"</span><span class="token punctuation">:</span> <span class="token number">90</span><span class="token punctuation">,</span> <span class="token string">"statements"</span><span class="token punctuation">:</span> <span class="token number">90</span> <span class="token punctuation">}</span> <span class="token punctuation">}</span><span class="token punctuation">,</span> <span class="token string">"coverageReporters"</span><span class="token punctuation">:</span> <span class="token punctuation">[</span><span class="token string">"text"</span><span class="token punctuation">]</span><span class="token punctuation">,</span> <span class="token string">"snapshotSerializers"</span><span class="token punctuation">:</span> <span class="token punctuation">[</span><span class="token string">"my-serializer-module"</span><span class="token punctuation">]</span> <span class="token punctuation">}</span> <span class="token punctuation">}</span> </code></pre> <h4>Continuous Integration</h4> <p>By default <code>npm test</code> runs the watcher with interactive CLI. However, you can force it to run tests once and finish the process by setting an environment variable called <code>CI</code>.</p> <p>When creating a build of your application with <code>npm run build</code> linter warnings are not checked by default. Like <code>npm test</code>, you can force the build to perform a linter warning check by setting the environment variable <code>CI</code>. If any warnings are encountered then the build fails.</p> <p>Popular CI servers already set the environment variable <code>CI</code> by default but you can do this yourself too:</p> <h4>On CI servers</h4> <h5>Travis CI</h5> <ol> <li>Following the Travis Getting started guide for syncing your GitHub repository with Travis. You may need to initialize some settings manually in your profile page.</li> <li>Add a <code>.travis.yml</code> file to your git repository.</li> </ol> <pre><code>language: node_js node_js: - 8 cache: directories: - node_modules script: - npm run build - npm test </code></pre> <ol> <li>Trigger your first build with a git push.</li> <li>Customize your Travis CI Build if needed.</li> </ol> <h5>CircleCI</h5> <p>Follow this article to set up CircleCI with a Create React App project.</p> <h4>On your own environment</h4> <h6>Windows (cmd.exe)</h6> <pre><code class="prism language-cmd">set CI=true&&npm test </code></pre> <pre><code class="prism language-cmd">set CI=true&&npm run build </code></pre> <p>(Note: the lack of whitespace is intentional.)</p> <h6>Windows (Powershell)</h6> <pre><code class="prism language-Powershell">($env:CI = $true) -and (npm test) </code></pre> <pre><code class="prism language-Powershell">($env:CI = $true) -and (npm run build) </code></pre> <h6>Linux, macOS (Bash)</h6> <pre><code class="prism language-bash">CI<span class="token operator">=</span>true <span class="token function">npm</span> <span class="token function">test</span> </code></pre> <pre><code class="prism language-bash">CI<span class="token operator">=</span>true <span class="token function">npm</span> run build </code></pre> <p>The test command will force Jest to run tests once instead of launching the watcher.</p> <blockquote> <p>If you find yourself doing this often in development, please file an issue to tell us about your use case because we want to make watcher the best experience and are open to changing how it works to accommodate more workflows.</p> </blockquote> <p>The build command will check for linter warnings and fail if any are found.</p> <h4>Disabling jsdom</h4> <p>If you know that none of your tests depend on jsdom, you can safely set <code>--env=node</code>, and your tests will run faster:</p> <pre><code class="prism language-diff"> "scripts": { "start": "react-scripts start", "build": "react-scripts build", - "test": "react-scripts test" + "test": "react-scripts test --env=node" </code></pre> <p>To help you make up your mind, here is a list of APIs that <strong>need jsdom</strong>:</p> <ul> <li>Any browser globals like <code>window</code> and <code>document</code></li> <li><code>ReactDOM.render()</code></li> <li><code>TestUtils.renderIntoDocument()</code> (a shortcut for the above)</li> <li><code>mount()</code> in Enzyme</li> </ul> <p>In contrast, <strong>jsdom is not needed</strong> for the following APIs:</p> <ul> <li><code>TestUtils.createRenderer()</code> (shallow rendering)</li> <li><code>shallow()</code> in Enzyme</li> </ul> <p>Finally, jsdom is also not needed for snapshot testing.</p> <h4>Snapshot Testing</h4> <p>Snapshot testing is a feature of Jest that automatically generates text snapshots of your components and saves them on the disk so if the UI output changes, you get notified without manually writing any assertions on the component output. Read more about snapshot testing.</p> <h4>Editor Integration</h4> <p>If you use Visual Studio Code, there is a Jest extension which works with Create React App out of the box. This provides a lot of IDE-like features while using a text editor: showing the status of a test run with potential fail messages inline, starting and stopping the watcher automatically, and offering one-click snapshot updates.</p> <p><img src="http://img.e-com-net.com/image/info8/fd9c9da699584e0faad9124883e4db87.jpg" alt="VS Code Jest Preview" width="0" height="0"></p> <h3>Debugging Tests</h3> <p>There are various ways to setup a debugger for your Jest tests. We cover debugging in Chrome and Visual Studio Code.</p> <blockquote> <p>Note: debugging tests requires Node 8 or higher.</p> </blockquote> <h4>Debugging Tests in Chrome</h4> <p>Add the following to the <code>scripts</code> section in your project’s <code>package.json</code></p> <pre><code class="prism language-json"><span class="token string">"scripts"</span><span class="token punctuation">:</span> <span class="token punctuation">{</span> <span class="token string">"test:debug"</span><span class="token punctuation">:</span> <span class="token string">"react-scripts --inspect-brk test --runInBand"</span> <span class="token punctuation">}</span> </code></pre> <p>Place <code>debugger;</code> statements in any test and run:</p> <pre><code class="prism language-bash">$ <span class="token function">npm</span> run test:debug </code></pre> <p>This will start running your Jest tests, but pause before executing to allow a debugger to attach to the process.</p> <p>Open the following in Chrome</p> <pre><code>about:inspect </code></pre> <p>After opening that link, the Chrome Developer Tools will be displayed. Select <code>inspect</code> on your process and a breakpoint will be set at the first line of the react script (this is done simply to give you time to open the developer tools and to prevent Jest from executing before you have time to do so). Click the button that looks like a “play” button in the upper right hand side of the screen to continue execution. When Jest executes the test that contains the debugger statement, execution will pause and you can examine the current scope and call stack.</p> <blockquote> <p>Note: the --runInBand cli option makes sure Jest runs test in the same process rather than spawning processes for individual tests. Normally Jest parallelizes test runs across processes but it is hard to debug many processes at the same time.</p> </blockquote> <h4>Debugging Tests in Visual Studio Code</h4> <p>Debugging Jest tests is supported out of the box for Visual Studio Code.</p> <p>Use the following <code>launch.json</code> configuration file:</p> <pre><code>{ "version": "0.2.0", "configurations": [ { "name": "Debug CRA Tests", "type": "node", "request": "launch", "runtimeExecutable": "${workspaceRoot}/node_modules/.bin/react-scripts", "args": [ "test", "--runInBand", "--no-cache" ], "cwd": "${workspaceRoot}", "protocol": "inspector", "console": "integratedTerminal", "internalConsoleOptions": "neverOpen" } ] } </code></pre> <h3>Developing Components in Isolation</h3> <p>Usually, in an app, you have a lot of UI components, and each of them has many different states.<br> For an example, a simple button component could have following states:</p> <ul> <li>In a regular state, with a text label.</li> <li>In the disabled mode.</li> <li>In a loading state.</li> </ul> <p>Usually, it’s hard to see these states without running a sample app or some examples.</p> <p>Create React App doesn’t include any tools for this by default, but you can easily add Storybook for React (source) or React Styleguidist (source) to your project. <strong>These are third-party tools that let you develop components and see all their states in isolation from your app</strong>.</p> <p></p> <p>You can also deploy your Storybook or style guide as a static app. This way, everyone in your team can view and review different states of UI components without starting a backend server or creating an account in your app.</p> <h4>Getting Started with Storybook</h4> <p>Storybook is a development environment for React UI components. It allows you to browse a component library, view the different states of each component, and interactively develop and test components.</p> <p>First, install the following npm package globally:</p> <pre><code class="prism language-sh">npm install -g @storybook/cli </code></pre> <p>Then, run the following command inside your app’s directory:</p> <pre><code class="prism language-sh">getstorybook </code></pre> <p>After that, follow the instructions on the screen.</p> <p>Learn more about React Storybook:</p> <ul> <li>Learn Storybook (tutorial)</li> <li>Documentation</li> <li>GitHub Repo</li> <li>Snapshot Testing UI with Storybook + addon/storyshot</li> </ul> <h4>Getting Started with Styleguidist</h4> <p>Styleguidist combines a style guide, where all your components are presented on a single page with their props documentation and usage examples, with an environment for developing components in isolation, similar to Storybook. In Styleguidist you write examples in Markdown, where each code snippet is rendered as a live editable playground.</p> <p>First, install Styleguidist:</p> <pre><code class="prism language-sh">npm install --save react-styleguidist </code></pre> <p>Alternatively you may use <code>yarn</code>:</p> <pre><code class="prism language-sh">yarn add react-styleguidist </code></pre> <p>Then, add these scripts to your <code>package.json</code>:</p> <pre><code class="prism language-diff"> "scripts": { + "styleguide": "styleguidist server", + "styleguide:build": "styleguidist build", "start": "react-scripts start", </code></pre> <p>Then, run the following command inside your app’s directory:</p> <pre><code class="prism language-sh">npm run styleguide </code></pre> <p>After that, follow the instructions on the screen.</p> <p>Learn more about React Styleguidist:</p> <ul> <li>GitHub Repo</li> <li>Documentation</li> </ul> <h3>Publishing Components to npm</h3> <p>Create React App doesn’t provide any built-in functionality to publish a component to npm. If you’re ready to extract a component from your project so other people can use it, we recommend moving it to a separate directory outside of your project and then using a tool like nwb to prepare it for publishing.</p> <h3>Making a Progressive Web App</h3> <p>The production build has all the tools necessary to generate a first-class<br> Progressive Web App,<br> but <strong>the offline/cache-first behavior is opt-in only</strong>. By default,<br> the build process will generate a service worker file, but it will not be<br> registered, so it will not take control of your production web app.</p> <p>In order to opt-in to the offline-first behavior, developers should look for the<br> following in their <code>src/index.js</code> file:</p> <pre><code class="prism language-js"><span class="token comment">// If you want your app to work offline and load faster, you can change</span> <span class="token comment">// unregister() to register() below. Note this comes with some pitfalls.</span> <span class="token comment">// Learn more about service workers: http://bit.ly/CRA-PWA</span> serviceWorker<span class="token punctuation">.</span><span class="token function">unregister</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> </code></pre> <p>As the comment states, switching <code>serviceWorker.unregister()</code> to<br> <code>serviceWorker.register()</code> will opt you in to using the service worker.</p> <h4>Why Opt-in?</h4> <p>Offline-first Progressive Web Apps are faster and more reliable than traditional web pages, and provide an engaging mobile experience:</p> <ul> <li>All static site assets are cached so that your page loads fast on subsequent visits, regardless of network connectivity (such as 2G or 3G). Updates are downloaded in the background.</li> <li>Your app will work regardless of network state, even if offline. This means your users will be able to use your app at 10,000 feet and on the subway.</li> <li>On mobile devices, your app can be added directly to the user’s home screen, app icon and all. This eliminates the need for the app store.</li> </ul> <p>However, they can make debugging deployments more challenging so, starting with Create React App 2, service workers are opt-in.</p> <p>The <code>workbox-webpack-plugin</code><br> is integrated into production configuration,<br> and it will take care of generating a service worker file that will automatically<br> precache all of your local assets and keep them up to date as you deploy updates.<br> The service worker will use a cache-first strategy<br> for handling all requests for local assets, including<br> navigation requests<br> for your HTML, ensuring that your web app is consistently fast, even on a slow<br> or unreliable network.</p> <h4>Offline-First Considerations</h4> <p>If you do decide to opt-in to service worker registration, please take the<br> following into account:</p> <ol> <li> <p>After the initial caching is done, the service worker lifecycle<br> controls when updated content ends up being shown to users. In order to guard against<br> race conditions with lazy-loaded content,<br> the default behavior is to conservatively keep the updated service worker in the “waiting”<br> state. This means that users will end up seeing older content until they close (reloading is not<br> enough) their existing, open tabs. See this blog post<br> for more details about this behavior.</p> </li> <li> <p>Users aren’t always familiar with offline-first web apps. It can be useful to<br> let the user know<br> when the service worker has finished populating your caches (showing a “This web<br> app works offline!” message) and also let them know when the service worker has<br> fetched the latest updates that will be available the next time they load the<br> page (showing a “New content is available once existing tabs are closed.” message). Showing<br> this messages is currently left as an exercise to the developer, but as a<br> starting point, you can make use of the logic included in <code>src/serviceWorker.js</code>, which<br> demonstrates which service worker lifecycle events to listen for to detect each<br> scenario, and which as a default, just logs appropriate messages to the<br> JavaScript console.</p> </li> <li> <p>Service workers require HTTPS,<br> although to facilitate local testing, that policy<br> does not apply to <code>localhost</code>.<br> If your production web server does not support HTTPS, then the service worker<br> registration will fail, but the rest of your web app will remain functional.</p> </li> <li> <p>The service worker is only enabled in the production environment,<br> e.g. the output of <code>npm run build</code>. It’s recommended that you do not enable an<br> offline-first service worker in a development environment, as it can lead to<br> frustration when previously cached assets are used and do not include the latest<br> changes you’ve made locally.</p> </li> <li> <p>If you <em>need</em> to test your offline-first service worker locally, build<br> the application (using <code>npm run build</code>) and run a simple http server from your<br> build directory. After running the build script, <code>create-react-app</code> will give<br> instructions for one way to test your production build locally and the deployment instructions have<br> instructions for using other methods. <em>Be sure to always use an<br> incognito window to avoid complications with your browser cache.</em></p> </li> <li> <p>By default, the generated service worker file will not intercept or cache any<br> cross-origin traffic, like HTTP API requests,<br> images, or embeds loaded from a different domain.</p> </li> </ol> <h4>Progressive Web App Metadata</h4> <p>The default configuration includes a web app manifest located at<br> <code>public/manifest.json</code>, that you can customize with<br> details specific to your web application.</p> <p>When a user adds a web app to their homescreen using Chrome or Firefox on<br> Android, the metadata in <code>manifest.json</code> determines what<br> icons, names, and branding colors to use when the web app is displayed.<br> The Web App Manifest guide<br> provides more context about what each field means, and how your customizations<br> will affect your users’ experience.</p> <p>Progressive web apps that have been added to the homescreen will load faster and<br> work offline when there’s an active service worker. That being said, the<br> metadata from the web app manifest will still be used regardless of whether or<br> not you opt-in to service worker registration.</p> <h3>Analyzing the Bundle Size</h3> <p>Source map explorer analyzes<br> JavaScript bundles using the source maps. This helps you understand where code<br> bloat is coming from.</p> <p>To add Source map explorer to a Create React App project, follow these steps:</p> <pre><code class="prism language-sh">npm install --save source-map-explorer </code></pre> <p>Alternatively you may use <code>yarn</code>:</p> <pre><code class="prism language-sh">yarn add source-map-explorer </code></pre> <p>Then in <code>package.json</code>, add the following line to <code>scripts</code>:</p> <pre><code class="prism language-diff"> "scripts": { + "analyze": "source-map-explorer build/static/js/main.*", "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", </code></pre> <p>Then to analyze the bundle run the production build then run the analyze<br> script.</p> <pre><code>npm run build npm run analyze </code></pre> <h3>Deployment</h3> <p><code>npm run build</code> creates a <code>build</code> directory with a production build of your app. Set up your favorite HTTP server so that a visitor to your site is served <code>index.html</code>, and requests to static paths like <code>/static/js/main.<hash>.js</code> are served with the contents of the <code>/static/js/main.<hash>.js</code> file.</p> <h4>Static Server</h4> <p>For environments using Node, the easiest way to handle this would be to install serve and let it handle the rest:</p> <pre><code class="prism language-sh">npm install -g serve serve -s build </code></pre> <p>The last command shown above will serve your static site on the port <strong>5000</strong>. Like many of serve’s internal settings, the port can be adjusted using the <code>-p</code> or <code>--port</code> flags.</p> <p>Run this command to get a full list of the options available:</p> <pre><code class="prism language-sh">serve -h </code></pre> <h4>Other Solutions</h4> <p>You don’t necessarily need a static server in order to run a Create React App project in production. It works just as fine integrated into an existing dynamic one.</p> <p>Here’s a programmatic example using Node and Express:</p> <pre><code class="prism language-javascript"><span class="token keyword">const</span> express <span class="token operator">=</span> <span class="token function">require</span><span class="token punctuation">(</span><span class="token string">'express'</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token keyword">const</span> path <span class="token operator">=</span> <span class="token function">require</span><span class="token punctuation">(</span><span class="token string">'path'</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token keyword">const</span> app <span class="token operator">=</span> <span class="token function">express</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> app<span class="token punctuation">.</span><span class="token function">use</span><span class="token punctuation">(</span>express<span class="token punctuation">.</span><span class="token keyword">static</span><span class="token punctuation">(</span>path<span class="token punctuation">.</span><span class="token function">join</span><span class="token punctuation">(</span>__dirname<span class="token punctuation">,</span> <span class="token string">'build'</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span> app<span class="token punctuation">.</span><span class="token keyword">get</span><span class="token punctuation">(</span><span class="token string">'/'</span><span class="token punctuation">,</span> <span class="token keyword">function</span><span class="token punctuation">(</span>req<span class="token punctuation">,</span> res<span class="token punctuation">)</span> <span class="token punctuation">{</span> res<span class="token punctuation">.</span><span class="token function">sendFile</span><span class="token punctuation">(</span>path<span class="token punctuation">.</span><span class="token function">join</span><span class="token punctuation">(</span>__dirname<span class="token punctuation">,</span> <span class="token string">'build'</span><span class="token punctuation">,</span> <span class="token string">'index.html'</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span> app<span class="token punctuation">.</span><span class="token function">listen</span><span class="token punctuation">(</span><span class="token number">9000</span><span class="token punctuation">)</span><span class="token punctuation">;</span> </code></pre> <p>The choice of your server software isn’t important either. Since Create React App is completely platform-agnostic, there’s no need to explicitly use Node.</p> <p>The <code>build</code> folder with static assets is the only output produced by Create React App.</p> <p>However this is not quite enough if you use client-side routing. Read the next section if you want to support URLs like <code>/todos/42</code> in your single-page app.</p> <h4>Serving Apps with Client-Side Routing</h4> <p>If you use routers that use the HTML5 <code>pushState</code> history API under the hood (for example, React Router with <code>browserHistory</code>), many static file servers will fail. For example, if you used React Router with a route for <code>/todos/42</code>, the development server will respond to <code>localhost:3000/todos/42</code> properly, but an Express serving a production build as above will not.</p> <p>This is because when there is a fresh page load for a <code>/todos/42</code>, the server looks for the file <code>build/todos/42</code> and does not find it. The server needs to be configured to respond to a request to <code>/todos/42</code> by serving <code>index.html</code>. For example, we can amend our Express example above to serve <code>index.html</code> for any unknown paths:</p> <pre><code class="prism language-diff"> app.use(express.static(path.join(__dirname, 'build'))); -app.get('/', function (req, res) { +app.get('/*', function (req, res) { res.sendFile(path.join(__dirname, 'build', 'index.html')); }); </code></pre> <p>If you’re using Apache HTTP Server, you need to create a <code>.htaccess</code> file in the <code>public</code> folder that looks like this:</p> <pre><code> Options -MultiViews RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.html [QSA,L] </code></pre> <p>It will get copied to the <code>build</code> folder when you run <code>npm run build</code>.</p> <p>If you’re using Apache Tomcat, you need to follow this Stack Overflow answer.</p> <p>Now requests to <code>/todos/42</code> will be handled correctly both in development and in production.</p> <p>On a production build, and when you’ve opted-in,<br> a service worker will automatically handle all navigation requests, like for<br> <code>/todos/42</code>, by serving the cached copy of your <code>index.html</code>. This<br> service worker navigation routing can be configured or disabled by<br> <code>eject</code>ing and then modifying the<br> <code>navigateFallback</code><br> and <code>navigateFallbackWhitelist</code><br> options of the <code>SWPreachePlugin</code> configuration.</p> <p>When users install your app to the homescreen of their device the default configuration will make a shortcut to <code>/index.html</code>. This may not work for client-side routers which expect the app to be served from <code>/</code>. Edit the web app manifest at <code>public/manifest.json</code> and change <code>start_url</code> to match the required URL scheme, for example:</p> <pre><code class="prism language-js"> <span class="token string">"start_url"</span><span class="token punctuation">:</span> <span class="token string">"."</span><span class="token punctuation">,</span> </code></pre> <h4>Building for Relative Paths</h4> <p>By default, Create React App produces a build assuming your app is hosted at the server root.<br><br> To override this, specify the <code>homepage</code> in your <code>package.json</code>, for example:</p> <pre><code class="prism language-js"> <span class="token string">"homepage"</span><span class="token punctuation">:</span> <span class="token string">"http://mywebsite.com/relativepath"</span><span class="token punctuation">,</span> </code></pre> <p>This will let Create React App correctly infer the root path to use in the generated HTML file.</p> <p><strong>Note</strong>: If you are using <code>react-router@^4</code>, you can root <code><Link></code>s using the <code>basename</code> prop on any <code><Router></code>.<br><br> More information here.<br><br> <br><br> For example:</p> <pre><code class="prism language-js"><span class="token operator"><</span>BrowserRouter basename<span class="token operator">=</span><span class="token string">"/calendar"</span><span class="token operator">/</span><span class="token operator">></span> <span class="token operator"><</span>Link to<span class="token operator">=</span><span class="token string">"/today"</span><span class="token operator">/</span><span class="token operator">></span> <span class="token comment">// renders <a href="/calendar/today"></span> </code></pre> <h5>Serving the Same Build from Different Paths</h5> <blockquote> <p>Note: this feature is available with <code>react-scripts@0.9.0</code> and higher.</p> </blockquote> <p>If you are not using the HTML5 <code>pushState</code> history API or not using client-side routing at all, it is unnecessary to specify the URL from which your app will be served. Instead, you can put this in your <code>package.json</code>:</p> <pre><code class="prism language-js"> <span class="token string">"homepage"</span><span class="token punctuation">:</span> <span class="token string">"."</span><span class="token punctuation">,</span> </code></pre> <p>This will make sure that all the asset paths are relative to <code>index.html</code>. You will then be able to move your app from <code>http://mywebsite.com</code> to <code>http://mywebsite.com/relativepath</code> or even <code>http://mywebsite.com/relative/path</code> without having to rebuild it.</p> <h4>Customizing Environment Variables for Arbitrary Build Environments</h4> <p>You can create an arbitrary build environment by creating a custom <code>.env</code> file and loading it using env-cmd.</p> <p>For example, to create a build environment for a staging environment:</p> <ol> <li>Create a file called <code>.env.staging</code></li> <li>Set environment variables as you would any other <code>.env</code> file (e.g. <code>REACT_APP_API_URL=http://api-staging.example.com</code>)</li> <li>Install env-cmd<pre><code class="prism language-sh">$ npm install env-cmd --save $ # or $ yarn add env-cmd </code></pre> </li> <li>Add a new script to your <code>package.json</code>, building with your new environment:<pre><code class="prism language-json"><span class="token punctuation">{</span> <span class="token string">"scripts"</span><span class="token punctuation">:</span> <span class="token punctuation">{</span> <span class="token string">"build:staging"</span><span class="token punctuation">:</span> <span class="token string">"env-cmd .env.staging npm run build"</span> <span class="token punctuation">}</span> <span class="token punctuation">}</span> </code></pre> </li> </ol> <p>Now you can run <code>npm run build:staging</code> to build with the staging environment config.<br> You can specify other environments in the same way.</p> <p>Variables in <code>.env.production</code> will be used as fallback because <code>NODE_ENV</code> will always be set to <code>production</code> for a build.</p> <h4>Azure</h4> <p>See this blog post on how to deploy your React app to Microsoft Azure.</p> <p>See this blog post or this repo for a way to use automatic deployment to Azure App Service.</p> <h4>Firebase</h4> <p>Install the Firebase CLI if you haven’t already by running <code>npm install -g firebase-tools</code>. Sign up for a Firebase account and create a new project. Run <code>firebase login</code> and login with your previous created Firebase account.</p> <p>Then run the <code>firebase init</code> command from your project’s root. You need to choose the <strong>Hosting: Configure and deploy Firebase Hosting sites</strong> and choose the Firebase project you created in the previous step. You will need to agree with <code>database.rules.json</code> being created, choose <code>build</code> as the public directory, and also agree to <strong>Configure as a single-page app</strong> by replying with <code>y</code>.</p> <pre><code class="prism language-sh"> === Project Setup First, let's associate this project directory with a Firebase project. You can create multiple project aliases by running firebase use --add, but for now we'll just set up a default project. ? What Firebase project do you want to associate as default? Example app (example-app-fd690) === Database Setup Firebase Realtime Database Rules allow you to define how your data should be structured and when your data can be read from and written to. ? What file should be used for Database Rules? database.rules.json ✔ Database Rules for example-app-fd690 have been downloaded to database.rules.json. Future modifications to database.rules.json will update Database Rules when you run firebase deploy. === Hosting Setup Your public directory is the folder (relative to your project directory) that will contain Hosting assets to uploaded with firebase deploy. If you have a build process for your assets, use your build's output directory. ? What do you want to use as your public directory? build ? Configure as a single-page app (rewrite all urls to /index.html)? Yes ✔ Wrote build/index.html i Writing configuration info to firebase.json... i Writing project information to .firebaserc... ✔ Firebase initialization complete! </code></pre> <p>IMPORTANT: you need to set proper HTTP caching headers for <code>service-worker.js</code> file in <code>firebase.json</code> file or you will not be able to see changes after first deployment (issue #2440). It should be added inside <code>"hosting"</code> key like next:</p> <pre><code>{ "hosting": { ... "headers": [ {"source": "/service-worker.js", "headers": [{"key": "Cache-Control", "value": "no-cache"}]} ] ... </code></pre> <p>Now, after you create a production build with <code>npm run build</code>, you can deploy it by running <code>firebase deploy</code>.</p> <pre><code class="prism language-sh"> === Deploying to 'example-app-fd690'... i deploying database, hosting ✔ database: rules ready to deploy. i hosting: preparing build directory for upload... Uploading: [============================== ] 75%✔ hosting: build folder uploaded successfully ✔ hosting: 8 files uploaded successfully i starting release process (may take several minutes)... ✔ Deploy complete! Project Console: https://console.firebase.google.com/project/example-app-fd690/overview Hosting URL: https://example-app-fd690.firebaseapp.com </code></pre> <p>For more information see Add Firebase to your JavaScript Project.</p> <h4>GitHub Pages</h4> <blockquote> <p>Note: this feature is available with <code>react-scripts@0.2.0</code> and higher.</p> </blockquote> <h5>Step 1: Add <code>homepage</code> to <code>package.json</code></h5> <p><strong>The step below is important!</strong><br><br> <strong>If you skip it, your app will not deploy correctly.</strong></p> <p>Open your <code>package.json</code> and add a <code>homepage</code> field for your project:</p> <pre><code class="prism language-json"> <span class="token string">"homepage"</span><span class="token punctuation">:</span> <span class="token string">"https://myusername.github.io/my-app"</span><span class="token punctuation">,</span> </code></pre> <p>or for a GitHub user page:</p> <pre><code class="prism language-json"> <span class="token string">"homepage"</span><span class="token punctuation">:</span> <span class="token string">"https://myusername.github.io"</span><span class="token punctuation">,</span> </code></pre> <p>or for a custom domain page:</p> <pre><code class="prism language-json"> <span class="token string">"homepage"</span><span class="token punctuation">:</span> <span class="token string">"https://mywebsite.com"</span><span class="token punctuation">,</span> </code></pre> <p>Create React App uses the <code>homepage</code> field to determine the root URL in the built HTML file.</p> <h5>Step 2: Install <code>gh-pages</code> and add <code>deploy</code> to <code>scripts</code> in <code>package.json</code></h5> <p>Now, whenever you run <code>npm run build</code>, you will see a cheat sheet with instructions on how to deploy to GitHub Pages.</p> <p>To publish it at https://myusername.github.io/my-app, run:</p> <pre><code class="prism language-sh">npm install --save gh-pages </code></pre> <p>Alternatively you may use <code>yarn</code>:</p> <pre><code class="prism language-sh">yarn add gh-pages </code></pre> <p>Add the following scripts in your <code>package.json</code>:</p> <pre><code class="prism language-diff"> "scripts": { + "predeploy": "npm run build", + "deploy": "gh-pages -d build", "start": "react-scripts start", "build": "react-scripts build", </code></pre> <p>The <code>predeploy</code> script will run automatically before <code>deploy</code> is run.</p> <p>If you are deploying to a GitHub user page instead of a project page you’ll need to make two<br> additional modifications:</p> <ol> <li>First, change your repository’s source branch to be any branch other than <strong>master</strong>.</li> <li>Additionally, tweak your <code>package.json</code> scripts to push deployments to <strong>master</strong>:</li> </ol> <pre><code class="prism language-diff"> "scripts": { "predeploy": "npm run build", - "deploy": "gh-pages -d build", + "deploy": "gh-pages -b master -d build", </code></pre> <h5>Step 3: Deploy the site by running <code>npm run deploy</code></h5> <p>Then run:</p> <pre><code class="prism language-sh">npm run deploy </code></pre> <h5>Step 4: Ensure your project’s settings use <code>gh-pages</code></h5> <p>Finally, make sure <strong>GitHub Pages</strong> option in your GitHub project settings is set to use the <code>gh-pages</code> branch:</p> <h5>Step 5: Optionally, configure the domain</h5> <p>You can configure a custom domain with GitHub Pages by adding a <code>CNAME</code> file to the <code>public/</code> folder.</p> <p>Your CNAME file should look like this:</p> <pre><code>mywebsite.com </code></pre> <h5>Notes on client-side routing</h5> <p>GitHub Pages doesn’t support routers that use the HTML5 <code>pushState</code> history API under the hood (for example, React Router using <code>browserHistory</code>). This is because when there is a fresh page load for a url like <code>http://user.github.io/todomvc/todos/42</code>, where <code>/todos/42</code> is a frontend route, the GitHub Pages server returns 404 because it knows nothing of <code>/todos/42</code>. If you want to add a router to a project hosted on GitHub Pages, here are a couple of solutions:</p> <ul> <li>You could switch from using HTML5 history API to routing with hashes. If you use React Router, you can switch to <code>hashHistory</code> for this effect, but the URL will be longer and more verbose (for example, <code>http://user.github.io/todomvc/#/todos/42?_k=yknaj</code>). Read more about different history implementations in React Router.</li> <li>Alternatively, you can use a trick to teach GitHub Pages to handle 404 by redirecting to your <code>index.html</code> page with a special redirect parameter. You would need to add a <code>404.html</code> file with the redirection code to the <code>build</code> folder before deploying your project, and you’ll need to add code handling the redirect parameter to <code>index.html</code>. You can find a detailed explanation of this technique in this guide.</li> </ul> <h5>Troubleshooting</h5> <h6>“/dev/tty: No such a device or address”</h6> <p>If, when deploying, you get <code>/dev/tty: No such a device or address</code> or a similar error, try the following:</p> <ol> <li>Create a new Personal Access Token</li> <li><code>git remote set-url origin https://<user>:<token>@github.com/<user>/<repo></code> .</li> <li>Try <code>npm run deploy</code> again</li> </ol> <h6>“Cannot read property ‘email’ of null”</h6> <p>If, when deploying, you get <code>Cannot read property 'email' of null</code>, try the following:</p> <ol> <li><code>git config --global user.name '<your_name>'</code></li> <li><code>git config --global user.email '<your_email>'</code></li> <li>Try <code>npm run deploy</code> again</li> </ol> <h4>Heroku</h4> <p>Use the Heroku Buildpack for Create React App.<br><br> You can find instructions in Deploying React with Zero Configuration.</p> <h5>Resolving Heroku Deployment Errors</h5> <p>Sometimes <code>npm run build</code> works locally but fails during deploy via Heroku. Following are the most common cases.</p> <h6>“Module not found: Error: Cannot resolve ‘file’ or ‘directory’”</h6> <p>If you get something like this:</p> <pre><code>remote: Failed to create a production build. Reason: remote: Module not found: Error: Cannot resolve 'file' or 'directory' MyDirectory in /tmp/build_1234/src </code></pre> <p>It means you need to ensure that the lettercase of the file or directory you <code>import</code> matches the one you see on your filesystem or on GitHub.</p> <p>This is important because Linux (the operating system used by Heroku) is case sensitive. So <code>MyDirectory</code> and <code>mydirectory</code> are two distinct directories and thus, even though the project builds locally, the difference in case breaks the <code>import</code> statements on Heroku remotes.</p> <h6>“Could not find a required file.”</h6> <p>If you exclude or ignore necessary files from the package you will see a error similar this one:</p> <pre><code>remote: Could not find a required file. remote: Name: `index.html` remote: Searched in: /tmp/build_a2875fc163b209225122d68916f1d4df/public remote: remote: npm ERR! Linux 3.13.0-105-generic remote: npm ERR! argv "/tmp/build_a2875fc163b209225122d68916f1d4df/.heroku/node/bin/node" "/tmp/build_a2875fc163b209225122d68916f1d4df/.heroku/node/bin/npm" "run" "build" </code></pre> <p>In this case, ensure that the file is there with the proper lettercase and that’s not ignored on your local <code>.gitignore</code> or <code>~/.gitignore_global</code>.</p> <h4>Netlify</h4> <p><strong>To do a manual deploy to Netlify’s CDN:</strong></p> <pre><code class="prism language-sh">npm install netlify-cli -g netlify deploy </code></pre> <p>Choose <code>build</code> as the path to deploy.</p> <p><strong>To setup continuous delivery:</strong></p> <p>With this setup Netlify will build and deploy when you push to git or open a pull request:</p> <ol> <li>Start a new netlify project</li> <li>Pick your Git hosting service and select your repository</li> <li>Click <code>Build your site</code></li> </ol> <p><strong>Support for client-side routing:</strong></p> <p>To support <code>pushState</code>, make sure to create a <code>public/_redirects</code> file with the following rewrite rules:</p> <pre><code>/* /index.html 200 </code></pre> <p>When you build the project, Create React App will place the <code>public</code> folder contents into the build output.</p> <h4>Now</h4> <p>Now offers a zero-configuration single-command deployment. You can use <code>now</code> to deploy your app for free.</p> <ol> <li> <p>Install the <code>now</code> command-line tool either via the recommended desktop tool or via node with <code>npm install -g now</code>.</p> </li> <li> <p>Build your app by running <code>npm run build</code>.</p> </li> <li> <p>Move into the build directory by running <code>cd build</code>.</p> </li> <li> <p>Run <code>now --name your-project-name</code> from within the build directory. You will see a <strong>now.sh</strong> URL in your output like this:</p> <pre><code>> Ready! https://your-project-name-tpspyhtdtk.now.sh (copied to clipboard) </code></pre> <p>Paste that URL into your browser when the build is complete, and you will see your deployed app.</p> </li> </ol> <p>Details are available in this article.</p> <h4>S3 and CloudFront</h4> <p>See this blog post on how to deploy your React app to Amazon Web Services S3 and CloudFront.</p> <h4>Surge</h4> <p>Install the Surge CLI if you haven’t already by running <code>npm install -g surge</code>. Run the <code>surge</code> command and log in you or create a new account.</p> <p>When asked about the project path, make sure to specify the <code>build</code> folder, for example:</p> <pre><code class="prism language-sh"> project path: /path/to/project/build </code></pre> <p>Note that in order to support routers that use HTML5 <code>pushState</code> API, you may want to rename the <code>index.html</code> in your build folder to <code>200.html</code> before deploying to Surge. This ensures that every URL falls back to that file.</p> <h3>Advanced Configuration</h3> <p>You can adjust various development and production settings by setting environment variables in your shell or with .env.</p> <table> <thead> <tr> <th align="center">Variable</th> <th align="center">Development</th> <th align="center">Production</th> <th align="left">Usage</th> </tr> </thead> <tbody> <tr> <td align="center">BROWSER</td> <td align="center">✅</td> <td align="center">❌</td> <td align="left">By default, Create React App will open the default system browser, favoring Chrome on macOS. Specify a browser to override this behavior, or set it to <code>none</code> to disable it completely. If you need to customize the way the browser is launched, you can specify a node script instead. Any arguments passed to <code>npm start</code> will also be passed to this script, and the url where your app is served will be the last argument. Your script’s file name must have the <code>.js</code> extension.</td> </tr> <tr> <td align="center">HOST</td> <td align="center">✅</td> <td align="center">❌</td> <td align="left">By default, the development web server binds to <code>localhost</code>. You may use this variable to specify a different host.</td> </tr> <tr> <td align="center">PORT</td> <td align="center">✅</td> <td align="center">❌</td> <td align="left">By default, the development web server will attempt to listen on port 3000 or prompt you to attempt the next available port. You may use this variable to specify a different port.</td> </tr> <tr> <td align="center">HTTPS</td> <td align="center">✅</td> <td align="center">❌</td> <td align="left">When set to <code>true</code>, Create React App will run the development server in <code>https</code> mode.</td> </tr> <tr> <td align="center">PUBLIC_URL</td> <td align="center">❌</td> <td align="center">✅</td> <td align="left">Create React App assumes your application is hosted at the serving web server’s root or a subpath as specified in <code>package.json</code> (<code>homepage</code>). Normally, Create React App ignores the hostname. You may use this variable to force assets to be referenced verbatim to the url you provide (hostname included). This may be particularly useful when using a CDN to host your application.</td> </tr> <tr> <td align="center">CI</td> <td align="center">?</td> <td align="center">✅</td> <td align="left">When set to <code>true</code>, Create React App treats warnings as failures in the build. It also makes the test runner non-watching. Most CIs set this flag by default.</td> </tr> <tr> <td align="center">REACT_EDITOR</td> <td align="center">✅</td> <td align="center">❌</td> <td align="left">When an app crashes in development, you will see an error overlay with clickable stack trace. When you click on it, Create React App will try to determine the editor you are using based on currently running processes, and open the relevant source file. You can send a pull request to detect your editor of choice. Setting this environment variable overrides the automatic detection. If you do it, make sure your systems PATH environment variable points to your editor’s bin folder. You can also set it to <code>none</code> to disable it completely.</td> </tr> <tr> <td align="center">CHOKIDAR_USEPOLLING</td> <td align="center">✅</td> <td align="center">❌</td> <td align="left">When set to <code>true</code>, the watcher runs in polling mode, as necessary inside a VM. Use this option if <code>npm start</code> isn’t detecting changes.</td> </tr> <tr> <td align="center">GENERATE_SOURCEMAP</td> <td align="center">❌</td> <td align="center">✅</td> <td align="left">When set to <code>false</code>, source maps are not generated for a production build. This solves OOM issues on some smaller machines.</td> </tr> <tr> <td align="center">NODE_PATH</td> <td align="center">✅</td> <td align="center">✅</td> <td align="left">Same as <code>NODE_PATH</code> in Node.js, but only relative folders are allowed. Can be handy for emulating a monorepo setup by setting <code>NODE_PATH=src</code>.</td> </tr> <tr> <td align="center">INLINE_RUNTIME_CHUNK</td> <td align="center">❌</td> <td align="center">✅</td> <td align="left">By default, Create React App will embed the runtime script into <code>index.html</code> during the production build. When set to <code>false</code>, the script will not be embedded and will be imported as usual. This is normally required when dealing with CSP.</td> </tr> </tbody> </table> <h3>Troubleshooting</h3> <h4><code>npm start</code> doesn’t detect changes</h4> <p>When you save a file while <code>npm start</code> is running, the browser should refresh with the updated code.<br><br> If this doesn’t happen, try one of the following workarounds:</p> <ul> <li>If your project is in a Dropbox folder, try moving it out.</li> <li>If the watcher doesn’t see a file called <code>index.js</code> and you’re referencing it by the folder name, you need to restart the watcher due to a Webpack bug.</li> <li>Some editors like Vim and IntelliJ have a “safe write” feature that currently breaks the watcher. You will need to disable it. Follow the instructions in “Adjusting Your Text Editor”.</li> <li>If your project path contains parentheses, try moving the project to a path without them. This is caused by a Webpack watcher bug.</li> <li>On Linux and macOS, you might need to tweak system settings to allow more watchers.</li> <li>If the project runs inside a virtual machine such as (a Vagrant provisioned) VirtualBox, create an <code>.env</code> file in your project directory if it doesn’t exist, and add <code>CHOKIDAR_USEPOLLING=true</code> to it. This ensures that the next time you run <code>npm start</code>, the watcher uses the polling mode, as necessary inside a VM.</li> </ul> <p>If none of these solutions help please leave a comment in this thread.</p> <h4><code>npm test</code> hangs or crashes on macOS Sierra</h4> <p>If you run <code>npm test</code> and the console gets stuck after printing <code>react-scripts test</code> to the console there might be a problem with your Watchman installation as described in facebook/create-react-app#713.</p> <p>We recommend deleting <code>node_modules</code> in your project and running <code>npm install</code> (or <code>yarn</code> if you use it) first. If it doesn’t help, you can try one of the numerous workarounds mentioned in these issues:</p> <ul> <li>facebook/jest#1767</li> <li>facebook/watchman#358</li> <li>ember-cli/ember-cli#6259</li> </ul> <p>It is reported that installing Watchman 4.7.0 or newer fixes the issue. If you use Homebrew, you can run these commands to update it:</p> <pre><code>watchman shutdown-server brew update brew reinstall watchman </code></pre> <p>You can find other installation methods on the Watchman documentation page.</p> <p>If this still doesn’t help, try running <code>launchctl unload -F ~/Library/LaunchAgents/com.github.facebook.watchman.plist</code>.</p> <p>There are also reports that <em>uninstalling</em> Watchman fixes the issue. So if nothing else helps, remove it from your system and try again.</p> <h4><code>npm run build</code> exits too early</h4> <p>It is reported that <code>npm run build</code> can fail on machines with limited memory and no swap space, which is common in cloud environments. Even with small projects this command can increase RAM usage in your system by hundreds of megabytes, so if you have less than 1 GB of available memory your build is likely to fail with the following message:</p> <blockquote> <p>The build failed because the process exited too early. This probably means the system ran out of memory or someone called <code>kill -9</code> on the process.</p> </blockquote> <p>If you are completely sure that you didn’t terminate the process, consider adding some swap space to the machine you’re building on, or build the project locally.</p> <h4><code>npm run build</code> fails on Heroku</h4> <p>This may be a problem with case sensitive filenames.<br> Please refer to this section.</p> <h4>Moment.js locales are missing</h4> <p>If you use a Moment.js, you might notice that only the English locale is available by default. This is because the locale files are large, and you probably only need a subset of all the locales provided by Moment.js.</p> <p>To add a specific Moment.js locale to your bundle, you need to import it explicitly.<br><br> For example:</p> <pre><code class="prism language-js"><span class="token keyword">import</span> moment <span class="token keyword">from</span> <span class="token string">'moment'</span><span class="token punctuation">;</span> <span class="token keyword">import</span> <span class="token string">'moment/locale/fr'</span><span class="token punctuation">;</span> </code></pre> <p>If you are importing multiple locales this way, you can later switch between them by calling <code>moment.locale()</code> with the locale name:</p> <pre><code class="prism language-js"><span class="token keyword">import</span> moment <span class="token keyword">from</span> <span class="token string">'moment'</span><span class="token punctuation">;</span> <span class="token keyword">import</span> <span class="token string">'moment/locale/fr'</span><span class="token punctuation">;</span> <span class="token keyword">import</span> <span class="token string">'moment/locale/es'</span><span class="token punctuation">;</span> <span class="token comment">// ...</span> moment<span class="token punctuation">.</span><span class="token function">locale</span><span class="token punctuation">(</span><span class="token string">'fr'</span><span class="token punctuation">)</span><span class="token punctuation">;</span> </code></pre> <p>This will only work for locales that have been explicitly imported before.</p> <h4><code>npm run build</code> fails to minify</h4> <p>Before <code>react-scripts@2.0.0</code>, this problem was caused by third party <code>node_modules</code> using modern JavaScript features because the minifier couldn’t handle them during the build. This has been solved by compiling standard modern JavaScript features inside <code>node_modules</code> in <code>react-scripts@2.0.0</code> and higher.</p> <p>If you’re seeing this error, you’re likely using an old version of <code>react-scripts</code>. You can either fix it by avoiding a dependency that uses modern syntax, or by upgrading to <code>react-scripts@>=2.0.0</code> and following the migration instructions in the changelog.</p> <h3>Alternatives to Ejecting</h3> <p>Ejecting lets you customize anything, but from that point on you have to maintain the configuration and scripts yourself. This can be daunting if you have many similar projects. In such cases instead of ejecting we recommend to <em>fork</em> <code>react-scripts</code> and any other packages you need. This article dives into how to do it in depth. You can find more discussion in this issue.</p> <h3>Something Missing?</h3> <p>If you have ideas for more “How To” recipes that should be on this page, let us know or contribute some!</p> </div> </div> </div> </div> </div> <!--PC和WAP自适应版--> <div id="SOHUCS" sid="1723060826409086976"></div> <script type="text/javascript" src="/views/front/js/chanyan.js"></script> <!-- 文章页-底部 动态广告位 --> <div class="youdao-fixed-ad" id="detail_ad_bottom"></div> </div> <div class="col-md-3"> <div class="row" id="ad"> <!-- 文章页-右侧1 动态广告位 --> <div id="right-1" class="col-lg-12 col-md-12 col-sm-4 col-xs-4 ad"> <div class="youdao-fixed-ad" id="detail_ad_1"> </div> </div> <!-- 文章页-右侧2 动态广告位 --> <div id="right-2" class="col-lg-12 col-md-12 col-sm-4 col-xs-4 ad"> <div class="youdao-fixed-ad" id="detail_ad_2"></div> </div> <!-- 文章页-右侧3 动态广告位 --> <div id="right-3" class="col-lg-12 col-md-12 col-sm-4 col-xs-4 ad"> <div class="youdao-fixed-ad" id="detail_ad_3"></div> </div> </div> </div> </div> </div> </div> <div class="container"> <h4 class="pt20 mb15 mt0 border-top">你可能感兴趣的:(transform,plato)</h4> <div id="paradigm-article-related"> <div class="recommend-post mb30"> <ul class="widget-links"> <li><a href="/article/1772765956330815488.htm" title="大模型的学习 LLaMa和ChatGLM,minichatgpt4" target="_blank">大模型的学习 LLaMa和ChatGLM,minichatgpt4</a> <span class="text-muted">贝猫说python</span> <a class="tag" taget="_blank" href="/search/%E5%AD%A6%E4%B9%A0/1.htm">学习</a><a class="tag" taget="_blank" href="/search/llama/1.htm">llama</a><a class="tag" taget="_blank" href="/search/%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD/1.htm">人工智能</a> <div>LLaMa和ChatGLM,minichatgpt4什么情况用Bert模型,什么情况用LLaMA、ChatGLM类大模型,咋选?答:Bert的模型由多层双向的Transformer编码器组成,由12层组成,768隐藏单元,12个head,总参数量110M,约1.15亿参数量。NLU(自然语言理解)任务效果很好,单卡GPU可以部署,速度快,V100GPU下1秒能处理2千条以上。ChatGLM-6B,</div> </li> <li><a href="/article/1770329526237200384.htm" title="chatGLM-6B部署报错quantization_kernels_parallel.so‘ (or one of its dependencies). Try using the full pat" target="_blank">chatGLM-6B部署报错quantization_kernels_parallel.so‘ (or one of its dependencies). Try using the full pat</a> <span class="text-muted">FL1623863129</span> <a class="tag" taget="_blank" href="/search/%E7%8E%AF%E5%A2%83%E9%85%8D%E7%BD%AE/1.htm">环境配置</a><a class="tag" taget="_blank" href="/search/%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0/1.htm">深度学习</a> <div>用python部署chatglm2时候报错:FileNotFoundError:Couldnotfindmodule'C:\Users\Administrator\.cache\huggingface\modules\transformers_modules\chatglm2-6b-int4\quantization_kernels_parallel.so'(oroneofitsdependenc</div> </li> <li><a href="/article/1769511592937979904.htm" title="论文阅读——SpectralGPT" target="_blank">论文阅读——SpectralGPT</a> <span class="text-muted">じんじん</span> <a class="tag" taget="_blank" href="/search/%E8%AE%BA%E6%96%87/1.htm">论文</a><a class="tag" taget="_blank" href="/search/%E8%AE%A1%E7%AE%97%E6%9C%BA%E8%A7%86%E8%A7%89/1.htm">计算机视觉</a><a class="tag" taget="_blank" href="/search/%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD/1.htm">人工智能</a> <div>SpectralGPT:SpectralFoundationModelSpectralGPT的通用RS基础模型,该模型专门用于使用新型3D生成预训练Transformer(GPT)处理光谱RS图像。重建损失由两个部分组成:令牌到令牌和频谱到频谱下游任务:</div> </li> <li><a href="/article/1769353496777261056.htm" title="突破编程_C++_C++11新特性(function与bind绑定器)" target="_blank">突破编程_C++_C++11新特性(function与bind绑定器)</a> <span class="text-muted">breakthrough_01</span> <a class="tag" taget="_blank" href="/search/c%2B%2B/1.htm">c++</a><a class="tag" taget="_blank" href="/search/%E5%BC%80%E5%8F%91%E8%AF%AD%E8%A8%80/1.htm">开发语言</a> <div>1可调用对象C++中的可调用对象(CallableObjects)是指那些能够被调用执行的对象。这包括了函数、函数对象(也叫做仿函数,即重载了operator()的类或者结构体)、Lambda表达式以及任何具有operator()的成员函数的对象。可调用对象在C++标准库算法(如std::for_each、std::transform等)以及回调函数等场景中广泛使用。1.1函数作为可调用对象任何普</div> </li> <li><a href="/article/1769299185112252416.htm" title="今日无更新" target="_blank">今日无更新</a> <span class="text-muted">我的昵称违规了</span> <div>学校的一个会忙得昏天黑地。明天有自己的一个发表,还要准备PPT,根据原来的改改就好……这周真的是有点繁杂了,搞定之后连着四五月份要写两篇论文,再加上五月底的课程论文还有紧接着的文献综述,看样子要疯……现在梳理一下自己手里的锤子:转到Pytorch,使用AllenNLP了解Transformer、了解LSTM了解jieba等分词工具了解Gensim等NLP处理工具接下来要做的:基于AllenNLP搞</div> </li> <li><a href="/article/1769112190029201408.htm" title="网页HTML5制作flex布局骰子,css3 flex布局结合transform生成一个3D骰子" target="_blank">网页HTML5制作flex布局骰子,css3 flex布局结合transform生成一个3D骰子</a> <span class="text-muted">weixin_39905500</span> <div>1Flex布局首先聊聊Flex布局,Flex布局又称“弹性布局”,任何容器都可以指定为Flex布局,设置Flex布局会使得子元素的float、clear、vertical-align失效1.1Flex属性1.1.1flex-direction:决定项目的排列方向,默认自左向右水平排列.box{flex-direction:row|row-reverse|column|column-reverse;</div> </li> <li><a href="/article/1768744251283275776.htm" title="YOLOv9改进 添加可变形注意力机制DAttention" target="_blank">YOLOv9改进 添加可变形注意力机制DAttention</a> <span class="text-muted">学yolo的小白</span> <a class="tag" taget="_blank" href="/search/UPgrade/1.htm">UPgrade</a><a class="tag" taget="_blank" href="/search/YOLOv9/1.htm">YOLOv9</a><a class="tag" taget="_blank" href="/search/YOLO/1.htm">YOLO</a><a class="tag" taget="_blank" href="/search/python/1.htm">python</a><a class="tag" taget="_blank" href="/search/%E7%9B%AE%E6%A0%87%E6%A3%80%E6%B5%8B/1.htm">目标检测</a><a class="tag" taget="_blank" href="/search/pytorch/1.htm">pytorch</a> <div>一、DeformableAttentionTransformer论文论文地址:arxiv.org/pdf/2201.00520.pdf二、DeformableAttentionTransformer注意力结构DeformableAttentionTransformer包含可变形注意力机制,允许模型根据输入的内容动态调整注意力权重。在传统的Transformer中,注意力是通过对查询和键向量之间的点</div> </li> <li><a href="/article/1768208631217586176.htm" title="图像算法实习生--面经1" target="_blank">图像算法实习生--面经1</a> <span class="text-muted">小豆包的小朋友0217</span> <a class="tag" taget="_blank" href="/search/%E7%AE%97%E6%B3%95/1.htm">算法</a> <div>系列文章目录文章目录系列文章目录前言一、为什么torch里面要用optimizer.zero_grad()进行梯度置0二、Unet神经网络为什么会在医学图像分割表现好?三、transformer相关问题四、介绍一下胶囊网络的动态路由五、yolo系列出到v9了,介绍一下你最熟悉的yolo算法六、一阶段目标检测算法和二阶段目标检测算法有什么区别?七、讲一下剪枝八、讲一下PTQandQAT量化的区别九、</div> </li> <li><a href="/article/1768162435069444096.htm" title="【学习总结】Python transformers AutoTokenizer encode 出现的 101 和 102" target="_blank">【学习总结】Python transformers AutoTokenizer encode 出现的 101 和 102</a> <span class="text-muted">爱学习的小道长</span> <a class="tag" taget="_blank" href="/search/AI/1.htm">AI</a><a class="tag" taget="_blank" href="/search/python/1.htm">python</a><a class="tag" taget="_blank" href="/search/%E5%AD%A6%E4%B9%A0/1.htm">学习</a><a class="tag" taget="_blank" href="/search/AI%E7%BC%96%E7%A8%8B/1.htm">AI编程</a> <div>1.代码展示:fromtransformersimportAutoTokenizer,AutoModelmodel_name="bert-base-chinese"tokenizer=AutoTokenizer.from_pretrained(model_name)model=AutoModel.from_pretrained(model_name)print(len(tokenizer.voca</div> </li> <li><a href="/article/1768027745792622592.htm" title="【古希腊罗马神话】期末问答题" target="_blank">【古希腊罗马神话】期末问答题</a> <span class="text-muted">MorleyOlsen</span> <a class="tag" taget="_blank" href="/search/%E8%8B%B1%E8%AF%AD%E5%85%AC%E9%80%89%E8%AF%BE%E7%B3%BB%E5%88%97/1.htm">英语公选课系列</a><a class="tag" taget="_blank" href="/search/%E8%8B%B1%E8%AF%AD/1.htm">英语</a> <div>Plato:1.Theobjectsthatweperceivewithoursensesaresimplyreflectionsoftheidealforms.Hencetheyareshadows,whilerealityisfoundintheformsthemselves.(sense)2.Wehaveasoulthatsurvivesusafterdeathandthatitisperm</div> </li> <li><a href="/article/1767816778269917184.htm" title="深度学习踩坑记录(持续更新)" target="_blank">深度学习踩坑记录(持续更新)</a> <span class="text-muted">芒果不茫QAQ</span> <a class="tag" taget="_blank" href="/search/%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0/1.htm">深度学习</a><a class="tag" taget="_blank" href="/search/%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD/1.htm">人工智能</a> <div>目录4060显卡cuda版本异常transformers初始化TrainingArguments时output_dir指定问题4060显卡cuda版本异常环境:torch1.11.0+cu113程序报错RuntimeError:nvrtc:error:invalidvaluefor--gpu-architecture(-arch)可能原因与解决办法4060显卡是sm_89架构,支持11.7以上cu</div> </li> <li><a href="/article/1767505730140700672.htm" title="小白看得懂的 Transformer" target="_blank">小白看得懂的 Transformer</a> <span class="text-muted">zy_zeros</span> <a class="tag" taget="_blank" href="/search/python/1.htm">python</a><a class="tag" taget="_blank" href="/search/%E5%BC%80%E5%8F%91%E8%AF%AD%E8%A8%80/1.htm">开发语言</a> <div>1.导语谷歌推出的BERT模型在11项NLP任务中夺得SOTA结果,引爆了整个NLP界。而BERT取得成功的一个关键因素是Transformer的强大作用。谷歌的Transformer模型最早是用于机器翻译任务,当时达到了SOTA效果。Transformer改进了RNN最被人诟病的训练慢的缺点,利用self-attention机制实现快速并行。并且Transformer可以增加到非常深的深度,充分</div> </li> <li><a href="/article/1767257748812136448.htm" title="大数据开发(Spark面试真题-卷六)" target="_blank">大数据开发(Spark面试真题-卷六)</a> <span class="text-muted">Key-Key</span> <a class="tag" taget="_blank" href="/search/%E5%A4%A7%E6%95%B0%E6%8D%AE/1.htm">大数据</a><a class="tag" taget="_blank" href="/search/spark/1.htm">spark</a><a class="tag" taget="_blank" href="/search/%E9%9D%A2%E8%AF%95/1.htm">面试</a> <div>大数据开发(Spark面试真题)1、SparkHashPartitioner和RangePartitioner的实现?2、SparkDAGScheduler、TaskScheduler、SchedulerBackend实现原理?3、介绍下Sparkclient提交application后,接下来的流程?4、Spark的cache和persist的区别?它们是transformation算子还是ac</div> </li> <li><a href="/article/1767056651694727168.htm" title="beam search原理与常见实现,与直接sample的区别" target="_blank">beam search原理与常见实现,与直接sample的区别</a> <span class="text-muted">samoyan</span> <a class="tag" taget="_blank" href="/search/LLM/1.htm">LLM</a><a class="tag" taget="_blank" href="/search/%E9%9D%A2%E8%AF%95/1.htm">面试</a><a class="tag" taget="_blank" href="/search/transformer/1.htm">transformer</a><a class="tag" taget="_blank" href="/search/%E9%9D%A2%E8%AF%95/1.htm">面试</a> <div>目录BeamSearch原理1.基本概念2.工作流程3.特点BeamSearch与直接Sample的区别1.确定性与随机性2.结果多样性3.性能与效率4.应用场景常见的BeamSearch实现1.TensorFlow库2.PyTorch库3.HuggingFace的Transformers库算法库和工具BeamSearch原理1.基本概念BeamSearch是一种启发式图搜索算法,常用于自然语言处</div> </li> <li><a href="/article/1766449693136609280.htm" title="【构建工具】Babel7.x快速配置" target="_blank">【构建工具】Babel7.x快速配置</a> <span class="text-muted">古狼_guwolf</span> <a class="tag" taget="_blank" href="/search/%E5%89%8D%E7%AB%AF%E5%BC%80%E5%8F%91/1.htm">前端开发</a><a class="tag" taget="_blank" href="/search/%E5%89%8D%E7%AB%AF/1.htm">前端</a> <div>1.安装依赖包npmi-D@babel/core@babel/cli@babel/preset-env@babel/plugin-transform-runtimenpmi-S@babel/polyfill@babel/runtime-corejs2@babel/core//Babel核心包@babel/preset-env//env预设,即很多插件的集合@babel/plugin-transfo</div> </li> <li><a href="/article/1766117254992322560.htm" title="Transformer、BERT和GPT 自然语言处理领域的重要模型" target="_blank">Transformer、BERT和GPT 自然语言处理领域的重要模型</a> <span class="text-muted">Jiang_Immortals</span> <a class="tag" taget="_blank" href="/search/%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD/1.htm">人工智能</a><a class="tag" taget="_blank" href="/search/%E8%87%AA%E7%84%B6%E8%AF%AD%E8%A8%80%E5%A4%84%E7%90%86/1.htm">自然语言处理</a><a class="tag" taget="_blank" href="/search/transformer/1.htm">transformer</a><a class="tag" taget="_blank" href="/search/bert/1.htm">bert</a> <div>Transformer、BERT和GPT都是自然语言处理领域的重要模型,它们之间有一些区别和联系。区别:架构:Transformer是一种基于自注意力机制的神经网络架构,用于编码输入序列和解码输出序列。BERT(BidirectionalEncoderRepresentationsfromTransformers)是基于Transformer架构的双向编码模型,用于学习上下文无关的词向量表示。GP</div> </li> <li><a href="/article/1765992130548948992.htm" title="[论文笔记] Transformer-XL" target="_blank">[论文笔记] Transformer-XL</a> <span class="text-muted">心心喵</span> <a class="tag" taget="_blank" href="/search/%E8%AE%BA%E6%96%87%E7%AC%94%E8%AE%B0/1.htm">论文笔记</a><a class="tag" taget="_blank" href="/search/transformer/1.htm">transformer</a><a class="tag" taget="_blank" href="/search/%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0/1.htm">深度学习</a><a class="tag" taget="_blank" href="/search/%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD/1.htm">人工智能</a> <div>这篇论文提出的Transformer-XL主要是针对Transformer在解决长依赖问题中受到固定长度上下文的限制,如Bert采用的Transformer最大上下文为512(其中是因为计算资源的限制,不是因为位置编码,因为使用的是绝对位置编码正余弦编码)。Transformer-XL能学习超过固定长度的依赖性,而不破坏时间一致性。它由段级递归机制和一种新的位置编码方案组成。该方法不仅能够捕获长期</div> </li> <li><a href="/article/1765894578470215680.htm" title="elementUI 样式小总结" target="_blank">elementUI 样式小总结</a> <span class="text-muted">前端开发小陈</span> <a class="tag" taget="_blank" href="/search/elementui/1.htm">elementui</a><a class="tag" taget="_blank" href="/search/vue.js/1.htm">vue.js</a><a class="tag" taget="_blank" href="/search/javascript/1.htm">javascript</a> <div>样式代码小总结1.弹窗居中显示,内容过高自行滚动。.dialog/deep/.el-dialog{display:flex;flex-direction:column;margin:0!important;position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);max-height:calc(100%-200px);max</div> </li> <li><a href="/article/1765573722602823680.htm" title="14:00开始面试,14:05就出来了,问题变态?" target="_blank">14:00开始面试,14:05就出来了,问题变态?</a> <span class="text-muted">weixin_49781735</span> <a class="tag" taget="_blank" href="/search/vue/1.htm">vue</a><a class="tag" taget="_blank" href="/search/%E5%89%8D%E7%AB%AF/1.htm">前端</a><a class="tag" taget="_blank" href="/search/vue/1.htm">vue</a> <div>1.如何操作让一个盒子右移50px,开销最小?//这种方式不会触发文档重排和重绘,性能开销很小。.box{transform:translateX(50px);}2.前端怎么判断一个密钥有没有被修改过?在前端中,可以使用数字签名来验证密钥是否被修改过。数字签名是一种用于验证数据完整性和认证来源的技术,常用于验证数据是否经过篡改。具体步骤如下:使用私钥对数据进行签名,生成数字签名。将数据和数字签名传</div> </li> <li><a href="/article/1765573596375244800.htm" title="ChatGPT介绍" target="_blank">ChatGPT介绍</a> <span class="text-muted">程序媛9688</span> <a class="tag" taget="_blank" href="/search/gpt/1.htm">gpt</a> <div>ChatGPT概述ChatGPT是一种前沿的大型语言模型(LargeLanguageModel,LLM),由人工智能研究组织OpenAI研发并推出。它基于Transformer架构,这是一种在自然语言处理(NLP)领域取得突破的深度学习方法。通过在海量的互联网文本数据上进行预训练,ChatGPT获得了强大的语言理解和生成能力。语言理解能力ChatGPT能够理解和分析复杂的自然语言文本。无论是用户提</div> </li> <li><a href="/article/1765367422979760128.htm" title="VisionLLaMA: A Unified LLaMA Interface for Vision Tasks" target="_blank">VisionLLaMA: A Unified LLaMA Interface for Vision Tasks</a> <span class="text-muted">liferecords</span> <a class="tag" taget="_blank" href="/search/LLM/1.htm">LLM</a><a class="tag" taget="_blank" href="/search/llama/1.htm">llama</a><a class="tag" taget="_blank" href="/search/%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0/1.htm">深度学习</a><a class="tag" taget="_blank" href="/search/%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD/1.htm">人工智能</a><a class="tag" taget="_blank" href="/search/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0/1.htm">机器学习</a><a class="tag" taget="_blank" href="/search/%E8%87%AA%E7%84%B6%E8%AF%AD%E8%A8%80%E5%A4%84%E7%90%86/1.htm">自然语言处理</a><a class="tag" taget="_blank" href="/search/%E7%AE%97%E6%B3%95/1.htm">算法</a> <div>VisionLLaMA:AUnifiedLLaMAInterfaceforVisionTasks相关链接:arxivgithub关键字:VisionLLaMA、visiontransformers、imagegeneration、imageclassification、semanticsegmentation摘要大型语言模型(LLMs)通常基于Transformer架构来处理文本输入。例如,LLa</div> </li> <li><a href="/article/1765172066971115520.htm" title="Sora - 探索AI视频模型的无限可能" target="_blank">Sora - 探索AI视频模型的无限可能</a> <span class="text-muted">nanshaws</span> <a class="tag" taget="_blank" href="/search/%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD/1.htm">人工智能</a> <div>方向一:技术解析Sora是OpenAI推出的一款先进的AI视频模型,它在技术上具有多个显著特点。首先,Sora能够处理和生成各种格式的视频,包括不同的时长、宽高比和分辨率,甚至能够生成长达一分钟的高清视频。这一特性使得Sora成为一个通用的视觉数据模型,适用于广泛的应用场景。其次,Sora在技术上采用了扩散型变换器(DiffusionTransformer)架构。这种架构结合了扩散模型和变换器模型</div> </li> <li><a href="/article/1764831451360092160.htm" title="转载--OpenAI视频生成模型Sora的全面解析:从ViViT、Diffusion Transformer到NaViT、VideoPoet" target="_blank">转载--OpenAI视频生成模型Sora的全面解析:从ViViT、Diffusion Transformer到NaViT、VideoPoet</a> <span class="text-muted">依然风yrlf</span> <a class="tag" taget="_blank" href="/search/%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD/1.htm">人工智能</a> <div>前言真没想到,距离视频生成上一轮的集中爆发(详见《Sora之前的视频生成发展史:从Gen2、EmuVideo到PixelDance、SVD、Pika1.0》)才过去三个月,没想OpenAI一出手,该领域又直接变天了自打2.16日OpenAI发布sora以来(其开发团队包括DALLE3的4作TimBrooks、DiT一作BillPeebles、三代DALLE的核心作者之一AdityaRamesh等1</div> </li> <li><a href="/article/1764599591128358912.htm" title="关于MediaEval数据集的Dataset构建(Text部分-使用PLM BERT)" target="_blank">关于MediaEval数据集的Dataset构建(Text部分-使用PLM BERT)</a> <span class="text-muted">Coisíní℘</span> <a class="tag" taget="_blank" href="/search/%E5%A4%9A%E6%A8%A1%E6%80%81%E8%99%9A%E5%81%87%E6%96%B0%E9%97%BB%E6%A3%80%E6%B5%8B/1.htm">多模态虚假新闻检测</a><a class="tag" taget="_blank" href="/search/bert/1.htm">bert</a><a class="tag" taget="_blank" href="/search/%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD/1.htm">人工智能</a><a class="tag" taget="_blank" href="/search/%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0/1.htm">深度学习</a> <div>importrandomimportnumpyasnpimportpandasaspdimporttorchfromtransformersimportBertModel,BertTokenizerfromtqdm.autoimporttqdmfromtorch.utils.dataimportDatasetimportre"""参考Game-On论文""""""util.py"""defset_</div> </li> <li><a href="/article/1764192884254400512.htm" title="Transformer结构介绍和Pyotrch代码实现" target="_blank">Transformer结构介绍和Pyotrch代码实现</a> <span class="text-muted">肆十二</span> <a class="tag" taget="_blank" href="/search/Pytorch%E8%AF%AD%E6%B3%95/1.htm">Pytorch语法</a><a class="tag" taget="_blank" href="/search/transformer/1.htm">transformer</a><a class="tag" taget="_blank" href="/search/%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0/1.htm">深度学习</a><a class="tag" taget="_blank" href="/search/%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD/1.htm">人工智能</a> <div>Transformer结构介绍和Pyotrch代码实现关注B站查看更多手把手教学:肆十二-的个人空间-肆十二-个人主页-哔哩哔哩视频(bilibili.com)基本结构介绍Transformer结构是近年来自然语言处理(NLP)领域的重要突破,它完全基于注意力机制(AttentionMechanism)来实现,克服了传统RNN模型无法并行计算以及容易丢失长距离依赖信息的问题。Transformer</div> </li> <li><a href="/article/1764053344239837184.htm" title="你下个Vite项目能不能用上Lightning CSS" target="_blank">你下个Vite项目能不能用上Lightning CSS</a> <span class="text-muted"></span> <div>Vite自从4.4版本开始实验性支持LightningCSS,可以让项目的CSS打包速度更快,构建体积更小,我们来一起看看在Vite中怎么配置使用LightningCSS吧。LightningCSS什么是LightningCSS引用官方的介绍:AnextremelyfastCSSparser,transformer,bundler,andminifier.一个非常快的CSS解析器、转换器、打包器和</div> </li> <li><a href="/article/1762823480509816832.htm" title="Mamba 作者谈 LLM 未来架构" target="_blank">Mamba 作者谈 LLM 未来架构</a> <span class="text-muted">JOYCE_Leo16</span> <a class="tag" taget="_blank" href="/search/Mamba/1.htm">Mamba</a><a class="tag" taget="_blank" href="/search/%E6%9E%B6%E6%9E%84/1.htm">架构</a><a class="tag" taget="_blank" href="/search/%E8%AE%A1%E7%AE%97%E6%9C%BA%E8%A7%86%E8%A7%89/1.htm">计算机视觉</a><a class="tag" taget="_blank" href="/search/%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0/1.htm">深度学习</a><a class="tag" taget="_blank" href="/search/transformer/1.htm">transformer</a><a class="tag" taget="_blank" href="/search/Mamba/1.htm">Mamba</a> <div>文章目录前言1、为什么注意力机制有效?2、注意力计算量呈平方级增长3、StripedHyena是个什么模型?4、什么是Mamba?5、Mamba硬件优化6、2024年架构预测7、对AI更多的预测本片文章来自【机器之心】对Mamba作者进行采访所进行的编译整理。前言在大模型领域,一直稳站C位的Transformer最近似乎有被超越的趋势。这个挑战者就是一项名为【Mamba】的研究,其在语言、音频和基</div> </li> <li><a href="/article/1762743576640446464.htm" title="千卡利用率超98%,详解JuiceFS在权威AI测试中的实现策略" target="_blank">千卡利用率超98%,详解JuiceFS在权威AI测试中的实现策略</a> <span class="text-muted"></span> <a class="tag" taget="_blank" href="/search/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD%E8%BF%90%E7%BB%B4/1.htm">机器学习人工智能运维</a> <div>2023年9月,AI领域的权威基准评测MLPerf推出了StorageBenchmark。该基准测试通过模拟机器学习I/O负载的方法,在不需要GPU的情况下就能进行大规模的性能压测,用以评估存储系统的在AI模型训练场景的适用性。目前支持两种模型训练:BERT(自然语言模型)和Unet3D(3D医学成像)。虽然目前不支持大语言模型如GPT、LLaMA,但BERT与大语言模型同为多层transform</div> </li> <li><a href="/article/1762719637369348096.htm" title="Transformer视频理解学习的笔记" target="_blank">Transformer视频理解学习的笔记</a> <span class="text-muted">LinlyZhai</span> <a class="tag" taget="_blank" href="/search/transformer/1.htm">transformer</a><a class="tag" taget="_blank" href="/search/%E5%AD%A6%E4%B9%A0/1.htm">学习</a><a class="tag" taget="_blank" href="/search/%E7%AC%94%E8%AE%B0/1.htm">笔记</a> <div>今天复习了Transformer,ViT,学了SwinTransformer,还有观看了B站视频理解沐神系列串讲视频上(24.2.26未看完,明天接着看)这里面更多论文见:https://github.com/mli/paper-reading/B站视频理解沐神系列串讲视频下(明天接着看)上面这张图中的知识蒸馏,可以回头看一下上面这个github网址论文:VideoTransformers:ASu</div> </li> <li><a href="/article/1762684518478733312.htm" title="基于深度学习的中文语音识别系统(毕设)" target="_blank">基于深度学习的中文语音识别系统(毕设)</a> <span class="text-muted">程序员奇奇</span> <a class="tag" taget="_blank" href="/search/%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0%E4%BB%8E%E5%85%A5%E9%97%A8%E5%88%B0%E7%B2%BE%E9%80%9A/1.htm">深度学习从入门到精通</a><a class="tag" taget="_blank" href="/search/%E8%AF%AD%E9%9F%B3%E8%AF%86%E5%88%AB/1.htm">语音识别</a><a class="tag" taget="_blank" href="/search/%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0/1.htm">深度学习</a><a class="tag" taget="_blank" href="/search/%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD/1.htm">人工智能</a> <div>该系统实现了基于深度框架的语音识别中的声学模型和语言模型建模,其中声学模型包括CNN-CTC、GRU-CTC、CNN-RNN-CTC,语言模型包含transformer、CBHG,数据集包含stc、primewords、Aishell、thchs30四个数据集。本项目现已训练一个迷你的语音识别系统,将项目下载到本地上,下载thchs数据集并解压至data,运行test.py,不出意外能够进行识别,</div> </li> <li><a href="/article/98.htm" title="微信开发者验证接口开发" target="_blank">微信开发者验证接口开发</a> <span class="text-muted">362217990</span> <a class="tag" taget="_blank" href="/search/%E5%BE%AE%E4%BF%A1+%E5%BC%80%E5%8F%91%E8%80%85+token+%E9%AA%8C%E8%AF%81/1.htm">微信 开发者 token 验证</a> <div>微信开发者接口验证。 Token,自己随便定义,与微信填写一致就可以了。 根据微信接入指南描述 http://mp.weixin.qq.com/wiki/17/2d4265491f12608cd170a95559800f2d.html 第一步:填写服务器配置 第二步:验证服务器地址的有效性 第三步:依据接口文档实现业务逻辑 这里主要讲第二步验证服务器有效性。 建一个</div> </li> <li><a href="/article/225.htm" title="一个小编程题-类似约瑟夫环问题" target="_blank">一个小编程题-类似约瑟夫环问题</a> <span class="text-muted">BrokenDreams</span> <a class="tag" taget="_blank" href="/search/%E7%BC%96%E7%A8%8B/1.htm">编程</a> <div>        今天群友出了一题:         一个数列,把第一个元素删除,然后把第二个元素放到数列的最后,依次操作下去,直到把数列中所有的数都删除,要求依次打印出这个过程中删除的数。      &</div> </li> <li><a href="/article/352.htm" title="linux复习笔记之bash shell (5) 关于减号-的作用" target="_blank">linux复习笔记之bash shell (5) 关于减号-的作用</a> <span class="text-muted">eksliang</span> <a class="tag" taget="_blank" href="/search/linux%E5%85%B3%E4%BA%8E%E5%87%8F%E5%8F%B7%E2%80%9C-%E2%80%9D%E7%9A%84%E5%90%AB%E4%B9%89/1.htm">linux关于减号“-”的含义</a><a class="tag" taget="_blank" href="/search/linux%E5%85%B3%E4%BA%8E%E5%87%8F%E5%8F%B7%E2%80%9C-%E2%80%9D%E7%9A%84%E7%94%A8%E9%80%94/1.htm">linux关于减号“-”的用途</a><a class="tag" taget="_blank" href="/search/linux%E5%85%B3%E4%BA%8E%E2%80%9C-%E2%80%9D%E7%9A%84%E5%90%AB%E4%B9%89/1.htm">linux关于“-”的含义</a><a class="tag" taget="_blank" href="/search/linux%E5%85%B3%E4%BA%8E%E5%87%8F%E5%8F%B7%E7%9A%84%E5%90%AB%E4%B9%89/1.htm">linux关于减号的含义</a> <div>    转载请出自出处: http://eksliang.iteye.com/blog/2105677        管道命令在bash的连续处理程序中是相当重要的,尤其在使用到前一个命令的studout(标准输出)作为这次的stdin(标准输入)时,就显得太重要了,某些命令需要用到文件名,例如上篇文档的的切割命令(split)、还有</div> </li> <li><a href="/article/479.htm" title="Unix(3)" target="_blank">Unix(3)</a> <span class="text-muted">18289753290</span> <a class="tag" taget="_blank" href="/search/unix+ksh/1.htm">unix ksh</a> <div>1)若该变量需要在其他子进程执行,则可用"$变量名称"或${变量}累加内容 什么是子进程?在我目前这个shell情况下,去打开一个新的shell,新的那个shell就是子进程。一般状态下,父进程的自定义变量是无法在子进程内使用的,但通过export将变量变成环境变量后就能够在子进程里面应用了。 2)条件判断: &&代表and  ||代表or&nbs</div> </li> <li><a href="/article/606.htm" title="关于ListView中性能优化中图片加载问题" target="_blank">关于ListView中性能优化中图片加载问题</a> <span class="text-muted">酷的飞上天空</span> <a class="tag" taget="_blank" href="/search/ListView/1.htm">ListView</a> <div>ListView的性能优化网上很多信息,但是涉及到异步加载图片问题就会出现问题。 具体参看上篇文章http://314858770.iteye.com/admin/blogs/1217594   如果每次都重新inflate一个新的View出来肯定会造成性能损失严重,可能会出现listview滚动是很卡的情况,还会出现内存溢出。 现在想出一个方法就是每次都添加一个标识,然后设置图</div> </li> <li><a href="/article/733.htm" title="德国总理默多克:给国人的一堂“震撼教育”课" target="_blank">德国总理默多克:给国人的一堂“震撼教育”课</a> <span class="text-muted">永夜-极光</span> <a class="tag" taget="_blank" href="/search/%E6%95%99%E8%82%B2/1.htm">教育</a> <div>http://bbs.voc.com.cn/topic-2443617-1-1.html德国总理默多克:给国人的一堂“震撼教育”课  安吉拉—默克尔,一位经历过社会主义的东德人,她利用自己的博客,发表一番来华前的谈话,该说的话,都在上面说了,全世界想看想传播——去看看默克尔总理的博客吧!   德国总理默克尔以她的低调、朴素、谦和、平易近人等品格给国人留下了深刻印象。她以实际行动为中国人上了一堂</div> </li> <li><a href="/article/860.htm" title="关于Java继承的一个小问题。。。" target="_blank">关于Java继承的一个小问题。。。</a> <span class="text-muted">随便小屋</span> <a class="tag" taget="_blank" href="/search/java/1.htm">java</a> <div>今天看Java 编程思想的时候遇见一个问题,运行的结果和自己想想的完全不一样。先把代码贴出来! //CanFight接口 interface Canfight { void fight(); } //ActionCharacter类 class ActionCharacter { public void fight() { System.out.pr</div> </li> <li><a href="/article/987.htm" title="23种基本的设计模式" target="_blank">23种基本的设计模式</a> <span class="text-muted">aijuans</span> <a class="tag" taget="_blank" href="/search/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/1.htm">设计模式</a> <div>Abstract Factory:提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。   Adapter:将一个类的接口转换成客户希望的另外一个接口。A d a p t e r模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。   Bridge:将抽象部分与它的实现部分分离,使它们都可以独立地变化。   Builder:将一个复杂对象的构建与它的表示分离,使得同</div> </li> <li><a href="/article/1114.htm" title="《周鸿祎自述:我的互联网方法论》读书笔记" target="_blank">《周鸿祎自述:我的互联网方法论》读书笔记</a> <span class="text-muted">aoyouzi</span> <a class="tag" taget="_blank" href="/search/%E8%AF%BB%E4%B9%A6%E7%AC%94%E8%AE%B0/1.htm">读书笔记</a> <div>从用户的角度来看,能解决问题的产品才是好产品,能方便/快速地解决问题的产品,就是一流产品.   商业模式不是赚钱模式 一款产品免费获得海量用户后,它的边际成本趋于0,然后再通过广告或者增值服务的方式赚钱,实际上就是创造了新的价值链.   商业模式的基础是用户,木有用户,任何商业模式都是浮云.商业模式的核心是产品,本质是通过产品为用户创造价值. 商业模式还包括寻找需求</div> </li> <li><a href="/article/1241.htm" title="JavaScript动态改变样式访问技术" target="_blank">JavaScript动态改变样式访问技术</a> <span class="text-muted">百合不是茶</span> <a class="tag" taget="_blank" href="/search/JavaScript/1.htm">JavaScript</a><a class="tag" taget="_blank" href="/search/style%E5%B1%9E%E6%80%A7/1.htm">style属性</a><a class="tag" taget="_blank" href="/search/ClassName%E5%B1%9E%E6%80%A7/1.htm">ClassName属性</a> <div>  一:style属性 格式:  HTML元素.style.样式属性="值";   创建菜单:在html标签中创建 或者 在head标签中用数组创建   <html> <head> <title>style改变样式</title> </head> &l</div> </li> <li><a href="/article/1368.htm" title="jQuery的deferred对象详解" target="_blank">jQuery的deferred对象详解</a> <span class="text-muted">bijian1013</span> <a class="tag" taget="_blank" href="/search/jquery/1.htm">jquery</a><a class="tag" taget="_blank" href="/search/deferred%E5%AF%B9%E8%B1%A1/1.htm">deferred对象</a> <div>        jQuery的开发速度很快,几乎每半年一个大版本,每两个月一个小版本。         每个版本都会引入一些新功能,从jQuery 1.5.0版本开始引入的一个新功能----deferred对象。    &nb</div> </li> <li><a href="/article/1495.htm" title="淘宝开放平台TOP" target="_blank">淘宝开放平台TOP</a> <span class="text-muted">Bill_chen</span> <a class="tag" taget="_blank" href="/search/C%2B%2B/1.htm">C++</a><a class="tag" taget="_blank" href="/search/c/1.htm">c</a><a class="tag" taget="_blank" href="/search/%E7%89%A9%E6%B5%81/1.htm">物流</a><a class="tag" taget="_blank" href="/search/C%23/1.htm">C#</a> <div>淘宝网开放平台首页:http://open.taobao.com/ 淘宝开放平台是淘宝TOP团队的产品,TOP即TaoBao Open Platform, 是淘宝合作伙伴开发、发布、交易其服务的平台。 支撑TOP的三条主线为:    1.开放数据和业务流程     * 以API数据形式开放商品、交易、物流等业务;  &</div> </li> <li><a href="/article/1622.htm" title="【大型网站架构一】大型网站架构概述" target="_blank">【大型网站架构一】大型网站架构概述</a> <span class="text-muted">bit1129</span> <a class="tag" taget="_blank" href="/search/%E7%BD%91%E7%AB%99%E6%9E%B6%E6%9E%84/1.htm">网站架构</a> <div>大型互联网特点 面对海量用户、海量数据 大型互联网架构的关键指标 高并发 高性能 高可用 高可扩展性 线性伸缩性 安全性 大型互联网技术要点   前端优化 CDN缓存 反向代理 KV缓存 消息系统 分布式存储 NoSQL数据库 搜索 监控 安全 想到的问题: 1.对于订单系统这种事务型系统,如</div> </li> <li><a href="/article/1749.htm" title="eclipse插件hibernate tools安装" target="_blank">eclipse插件hibernate tools安装</a> <span class="text-muted">白糖_</span> <a class="tag" taget="_blank" href="/search/Hibernate/1.htm">Hibernate</a> <div> eclipse helios(3.6)版 1.启动eclipse 2.选择 Help > Install New Software...> 3.添加如下地址: http://download.jboss.org/jbosstools/updates/stable/helios/ 4.选择性安装:hibernate tools在All Jboss tool</div> </li> <li><a href="/article/1876.htm" title="Jquery easyui Form表单提交注意事项" target="_blank">Jquery easyui Form表单提交注意事项</a> <span class="text-muted">bozch</span> <a class="tag" taget="_blank" href="/search/jquery+easyui/1.htm">jquery easyui</a> <div>jquery easyui对表单的提交进行了封装,提交的方式采用的是ajax的方式,在开发的时候应该注意的事项如下:         1、在定义form标签的时候,要将method属性设置成post或者get,特别是进行大字段的文本信息提交的时候,要将method设置成post方式提交,否则页面会抛出跨域访问等异常。所以这个要</div> </li> <li><a href="/article/2003.htm" title="Trie tree(字典树)的Java实现及其应用-统计以某字符串为前缀的单词的数量" target="_blank">Trie tree(字典树)的Java实现及其应用-统计以某字符串为前缀的单词的数量</a> <span class="text-muted">bylijinnan</span> <a class="tag" taget="_blank" href="/search/java%E5%AE%9E%E7%8E%B0/1.htm">java实现</a> <div> import java.util.LinkedList; public class CaseInsensitiveTrie { /** 字典树的Java实现。实现了插入、查询以及深度优先遍历。 Trie tree's java implementation.(Insert,Search,DFS) Problem Description Igna</div> </li> <li><a href="/article/2130.htm" title="html css 鼠标形状样式汇总" target="_blank">html css 鼠标形状样式汇总</a> <span class="text-muted">chenbowen00</span> <a class="tag" taget="_blank" href="/search/html/1.htm">html</a><a class="tag" taget="_blank" href="/search/css/1.htm">css</a> <div>css鼠标手型cursor中hand与pointer  Example:CSS鼠标手型效果 <a href="#" style="cursor:hand">CSS鼠标手型效果</a><br/>  Example:CSS鼠标手型效果 <a href="#" style=&qu</div> </li> <li><a href="/article/2257.htm" title="[IT与投资]IT投资的几个原则" target="_blank">[IT与投资]IT投资的几个原则</a> <span class="text-muted">comsci</span> <a class="tag" taget="_blank" href="/search/it/1.htm">it</a> <div>       无论是想在电商,软件,硬件还是互联网领域投资,都需要大量资金,虽然各个国家政府在媒体上都给予大家承诺,既要让市场的流动性宽松,又要保持经济的高速增长....但是,事实上,整个市场和社会对于真正的资金投入是非常渴望的,也就是说,表面上看起来,市场很活跃,但是投入的资金并不是很充足的......    </div> </li> <li><a href="/article/2384.htm" title="oracle with语句详解" target="_blank">oracle with语句详解</a> <span class="text-muted">daizj</span> <a class="tag" taget="_blank" href="/search/oracle/1.htm">oracle</a><a class="tag" taget="_blank" href="/search/with/1.htm">with</a><a class="tag" taget="_blank" href="/search/with+as/1.htm">with as</a> <div>oracle with语句详解 转 在oracle中,select 查询语句,可以使用with,就是一个子查询,oracle 会把子查询的结果放到临时表中,可以反复使用 例子:注意,这是sql语句,不是pl/sql语句, 可以直接放到jdbc执行的 ----------------------------------------------------------------</div> </li> <li><a href="/article/2511.htm" title="hbase的简单操作" target="_blank">hbase的简单操作</a> <span class="text-muted">deng520159</span> <a class="tag" taget="_blank" href="/search/%E6%95%B0%E6%8D%AE%E5%BA%93/1.htm">数据库</a><a class="tag" taget="_blank" href="/search/hbase/1.htm">hbase</a> <div>近期公司用hbase来存储日志,然后再来分析 ,把hbase开发经常要用的命令找了出来. 用ssh登陆安装hbase那台linux后 用hbase shell进行hbase命令控制台! 表的管理 1)查看有哪些表 hbase(main)> list 2)创建表   # 语法:create <table>, {NAME => <family&g</div> </li> <li><a href="/article/2638.htm" title="C语言scanf继续学习、算术运算符学习和逻辑运算符" target="_blank">C语言scanf继续学习、算术运算符学习和逻辑运算符</a> <span class="text-muted">dcj3sjt126com</span> <a class="tag" taget="_blank" href="/search/c/1.htm">c</a> <div>/* 2013年3月11日20:37:32 地点:北京潘家园 功能:完成用户格式化输入多个值 目的:学习scanf函数的使用 */ # include <stdio.h> int main(void) { int i, j, k; printf("please input three number:\n"); //提示用</div> </li> <li><a href="/article/2765.htm" title="2015越来越好" target="_blank">2015越来越好</a> <span class="text-muted">dcj3sjt126com</span> <a class="tag" taget="_blank" href="/search/%E6%AD%8C%E6%9B%B2/1.htm">歌曲</a> <div>越来越好 房子大了电话小了 感觉越来越好 假期多了收入高了 工作越来越好 商品精了价格活了 心情越来越好 天更蓝了水更清了 环境越来越好 活得有奔头人会步步高 想做到你要努力去做到 幸福的笑容天天挂眉梢 越来越好 婆媳和了家庭暖了 生活越来越好 孩子高了懂事多了 学习越来越好 朋友多了心相通了 大家越来越好 道路宽了心气顺了 日子越来越好 活的有精神人就不显</div> </li> <li><a href="/article/2892.htm" title="java.sql.SQLException: Value '0000-00-00' can not be represented as java.sql.Tim" target="_blank">java.sql.SQLException: Value '0000-00-00' can not be represented as java.sql.Tim</a> <span class="text-muted">feiteyizu</span> <a class="tag" taget="_blank" href="/search/mysql/1.htm">mysql</a> <div>数据表中有记录的time字段(属性为timestamp)其值为:“0000-00-00 00:00:00” 程序使用select 语句从中取数据时出现以下异常: java.sql.SQLException:Value '0000-00-00' can not be represented as java.sql.Date   java.sql.SQLException: Valu</div> </li> <li><a href="/article/3019.htm" title="Ehcache(07)——Ehcache对并发的支持" target="_blank">Ehcache(07)——Ehcache对并发的支持</a> <span class="text-muted">234390216</span> <a class="tag" taget="_blank" href="/search/%E5%B9%B6%E5%8F%91/1.htm">并发</a><a class="tag" taget="_blank" href="/search/ehcache/1.htm">ehcache</a><a class="tag" taget="_blank" href="/search/%E9%94%81/1.htm">锁</a><a class="tag" taget="_blank" href="/search/ReadLock/1.htm">ReadLock</a><a class="tag" taget="_blank" href="/search/WriteLock/1.htm">WriteLock</a> <div>Ehcache对并发的支持          在高并发的情况下,使用Ehcache缓存时,由于并发的读与写,我们读的数据有可能是错误的,我们写的数据也有可能意外的被覆盖。所幸的是Ehcache为我们提供了针对于缓存元素Key的Read(读)、Write(写)锁。当一个线程获取了某一Key的Read锁之后,其它线程获取针对于同</div> </li> <li><a href="/article/3146.htm" title="mysql中blob,text字段的合成索引" target="_blank">mysql中blob,text字段的合成索引</a> <span class="text-muted">jackyrong</span> <a class="tag" taget="_blank" href="/search/mysql/1.htm">mysql</a> <div>  在mysql中,原来有一个叫合成索引的,可以提高blob,text字段的效率性能, 但只能用在精确查询,核心是增加一个列,然后可以用md5进行散列,用散列值查找 则速度快 比如: create table abc(id varchar(10),context blog,hash_value varchar(40)); insert into abc(1,rep</div> </li> <li><a href="/article/3273.htm" title="逻辑运算与移位运算" target="_blank">逻辑运算与移位运算</a> <span class="text-muted">latty</span> <a class="tag" taget="_blank" href="/search/%E4%BD%8D%E8%BF%90%E7%AE%97/1.htm">位运算</a><a class="tag" taget="_blank" href="/search/%E9%80%BB%E8%BE%91%E8%BF%90%E7%AE%97/1.htm">逻辑运算</a> <div>源码:正数的补码与原码相同例+7 源码:00000111 补码 :00000111 (用8位二进制表示一个数) 负数的补码: 符号位为1,其余位为该数绝对值的原码按位取反;然后整个数加1。   -7 源码: 10000111 ,其绝对值为00000111  取反加一:11111001 为-7补码 已知一个数的补码,求原码的操作分两种情况:</div> </li> <li><a href="/article/3400.htm" title="利用XSD 验证XML文件" target="_blank">利用XSD 验证XML文件</a> <span class="text-muted">newerdragon</span> <a class="tag" taget="_blank" href="/search/java/1.htm">java</a><a class="tag" taget="_blank" href="/search/xml/1.htm">xml</a><a class="tag" taget="_blank" href="/search/xsd/1.htm">xsd</a> <div>XSD文件 (XML Schema 语言也称作 XML Schema 定义(XML Schema Definition,XSD)。 具体使用方法和定义请参看: http://www.w3school.com.cn/schema/index.asp java自jdk1.5以上新增了SchemaFactory类 可以实现对XSD验证的支持,使用起来也很方便。 以下代码可用在J</div> </li> <li><a href="/article/3527.htm" title="搭建 CentOS 6 服务器(12) - Samba" target="_blank">搭建 CentOS 6 服务器(12) - Samba</a> <span class="text-muted">rensanning</span> <a class="tag" taget="_blank" href="/search/centos/1.htm">centos</a> <div>(1)安装 # yum -y install samba Installed: samba.i686 0:3.6.9-169.el6_5 # pdbedit -a rensn new password:123456 retype new password:123456 …… (2)Home文件夹 # mkdir /etc</div> </li> <li><a href="/article/3654.htm" title="Learn Nodejs 01" target="_blank">Learn Nodejs 01</a> <span class="text-muted">toknowme</span> <a class="tag" taget="_blank" href="/search/nodejs/1.htm">nodejs</a> <div>(1)下载nodejs https://nodejs.org/download/ 选择相应的版本进行下载     (2)安装nodejs 安装的方式比较多,请baidu下 我这边下载的是“node-v0.12.7-linux-x64.tar.gz”这个版本 (1)上传服务器 (2)解压 tar -zxvf  node-v0.12.</div> </li> <li><a href="/article/3781.htm" title="jquery控制自动刷新的代码举例" target="_blank">jquery控制自动刷新的代码举例</a> <span class="text-muted">xp9802</span> <a class="tag" taget="_blank" href="/search/jquery/1.htm">jquery</a> <div>1、html内容部分  复制代码代码示例: <div id='log_reload'> <select name="id_s" size="1"> <option value='2'>-2s-</option> <option value='3'>-3s-</option</div> </li> </ul> </div> </div> </div> <div> <div class="container"> <div class="indexes"> <strong>按字母分类:</strong> <a href="/tags/A/1.htm" target="_blank">A</a><a href="/tags/B/1.htm" target="_blank">B</a><a href="/tags/C/1.htm" target="_blank">C</a><a href="/tags/D/1.htm" target="_blank">D</a><a href="/tags/E/1.htm" target="_blank">E</a><a href="/tags/F/1.htm" target="_blank">F</a><a href="/tags/G/1.htm" target="_blank">G</a><a href="/tags/H/1.htm" target="_blank">H</a><a href="/tags/I/1.htm" target="_blank">I</a><a href="/tags/J/1.htm" target="_blank">J</a><a href="/tags/K/1.htm" target="_blank">K</a><a href="/tags/L/1.htm" target="_blank">L</a><a href="/tags/M/1.htm" target="_blank">M</a><a href="/tags/N/1.htm" target="_blank">N</a><a href="/tags/O/1.htm" target="_blank">O</a><a href="/tags/P/1.htm" target="_blank">P</a><a href="/tags/Q/1.htm" target="_blank">Q</a><a href="/tags/R/1.htm" target="_blank">R</a><a href="/tags/S/1.htm" target="_blank">S</a><a href="/tags/T/1.htm" target="_blank">T</a><a href="/tags/U/1.htm" target="_blank">U</a><a href="/tags/V/1.htm" target="_blank">V</a><a href="/tags/W/1.htm" target="_blank">W</a><a href="/tags/X/1.htm" target="_blank">X</a><a href="/tags/Y/1.htm" target="_blank">Y</a><a href="/tags/Z/1.htm" target="_blank">Z</a><a href="/tags/0/1.htm" target="_blank">其他</a> </div> </div> </div> <footer id="footer" class="mb30 mt30"> <div class="container"> <div class="footBglm"> <a target="_blank" href="/">首页</a> - <a target="_blank" href="/custom/about.htm">关于我们</a> - <a target="_blank" href="/search/Java/1.htm">站内搜索</a> - <a target="_blank" href="/sitemap.txt">Sitemap</a> - <a target="_blank" href="/custom/delete.htm">侵权投诉</a> </div> <div class="copyright">版权所有 IT知识库 CopyRight © 2000-2050 E-COM-NET.COM , All Rights Reserved. <!-- <a href="https://beian.miit.gov.cn/" rel="nofollow" target="_blank">京ICP备09083238号</a><br>--> </div> </div> </footer> <!-- 代码高亮 --> <script type="text/javascript" src="/static/syntaxhighlighter/scripts/shCore.js"></script> <script type="text/javascript" src="/static/syntaxhighlighter/scripts/shLegacy.js"></script> <script type="text/javascript" src="/static/syntaxhighlighter/scripts/shAutoloader.js"></script> <link type="text/css" rel="stylesheet" href="/static/syntaxhighlighter/styles/shCoreDefault.css"/> <script type="text/javascript" src="/static/syntaxhighlighter/src/my_start_1.js"></script> </body> </html>