Development

2017-03-11  本文已影响0人  前端xiyoki

原文地址:https://webpack.js.org/guides/development/
翻译:xiyoki

Development(开发)

本页将解释如何开始开发,以及如何选择三个工具中的一个来开发。
假设你已经有了一个webpack配置文件。

Adjusting Your Text Editor(调整你的文本编辑器)

一些文本编辑器有一个 "safe write"功能,并且默认是启用的。因此,点击保存文件并不会使得文件被重新编译。

对不同的编辑器禁用该功能的方式是不同。下面是针对最常见的编辑器的设置:

Source Maps

当JavaScript出现异常,你会想知道哪个文件,哪一行产生了这个错误。由于webpack输出files到一个或多个bundle中,跟踪文件就不太方便。
Source maps 致力于解决这个问题。这里有不同的选项,每个选项既有优点也有缺点。为了开始,你可以选用这个:

devtool: "cheap-module-source-map"

devtool还有其他值供你选择,详见配置项devtool

Choosing a Tool(选择一个工具)

这里有三个工具供你选择:

在大多数情况下,你会想要使用webpack-dev-server,因为使用它开始是最容易的,并且它也提供了很多盒子之外( out-of-the-box)的功能。

webpack Watch Mode

...略。详情请查看原文。

webpack-dev-server

webpack-dev-server提供了一个server,以及live reloading(自动加载)的功能。它很容易设置。

准备工作: 确保你有一个index.html文件,打包后的文件内嵌其中。 假设output.filenamebundle.js:

<script src="/bundle.js"></script>

开始通过npm安装webpack-dev-server:

npm install webpack-dev-server --save-dev

当安装完成,你应当像这样使用webpack-dev-server:

webpack-dev-server --open

如果你的控制台报告找到不到这个命令,那么就尝试运行 node_modules/.bin/webpack-dev-server --open。最佳方式是将这个命令添加进package.json, 就像这样:

 "scripts": { "start": "webpack-dev-server --open" }

上述命令会自动在http://localhost:8080下打开你的浏览器。

Make a change in one of your files and hit save. You should see that the console is recompiling. After that's done, the page should be refreshed. If nothing happens in the console, you may need to fiddle with watchOptions
.

Now you have live reloading working, you can take it even a step further: Hot Module Replacement. This is an interface that makes it possible to swap modules without a page refresh. Find out how to configure HMR.

个人补充:如果只需实现React模块的热加载,那么使用Babel中的react-transform-hrm插件,可以在不对React模块进行额外配置的前提下让HMR正常工作,即可以更方便的实现React模块的热加载。
具体操作:

cnpm install --save-dev babel-plugin-react-transform react-transform-hmr
//webpack.config.js
var webpack = require("webpack");
module.exports = {
  ...
  plugins: [
    ...
    new webpack.HotModuleReplacementPlugin()//热加载插件
  ],
  devServer: {
    ...
    hot: true
  }
}
//.babelrc
{
  "presets": ["react", "es2015"],
  "env": {
    "development": {
    "plugins": [["react-transform", {
       "transforms": [{
         "transform": "react-transform-hmr",
         "imports": ["react"],
         "locals": ["module"]
       }]
     }]]
    }
  }
}

详细参考zhangwang翻译的这篇文章

默认使用inline模式 。This mode injects the client - needed for live reloading and showing build errors - in your bundle. With inline mode you will get build errors and warnings in your DevTools console. more information about inline.

webpack-dev-server可以做更多的事,比如为后端server代理请求(proxying requests) 。更多配置选项,查看devServer documentation

webpack-dev-middleware

...略。详情请查看原文。

上一篇 下一篇

猜你喜欢

热点阅读