用webpack配置Riot Redux工程

  • 2019 年 12 月 4 日
  • 笔记

本文作者:IMWeb 黄龙 原文出处:IMWeb社区 未经同意,禁止转载

名词介绍

webpack是一款模块加载器兼打包工具,它能把各种资源,例如JS(含JSX)、coffee、样式(含less/sass)、图片Riot的tag文件等都作为模块来使用和处理。我们可以直接使用 require(XXX) 的形式来引入各模块。

Riot是一个类似React的微型 UI 库,具体可以见【微型UI库Riot介绍】

Redux 是 JavaScript状态容器,提供可预测化的状态管理。

配置项目

1.首先创建package.json文件

mkdir riot-redux  cd riot-redux  npm init

2.安装

给package.json添加依赖描述

...  "scripts": {          "dev": "webpack-dev-server"      },  ...  "dependencies": {          "babel-core": "^6.3.17",          "babel-loader": "^6.2.0",          "babel-preset-es2015": "^6.3.13",          "redux": "^3.5.2",          "redux-thunk": "^1.0.2",          "riot": "^2.3.18",          "tag-loader": "^0.3.0",          "webpack": "^1.13.0",          "webpack-dev-server": "^1.14.1"      }
npm install

3.配置

每个webpack项目下都有一个 webpack.config.js ,它的作用如同gulp的gulp.js或者fis3的fis-conf.js ,就是一个配置项,告诉 webpack 它需要做什么。

module.exports = {      // 页面入口文件配置      entry: './src/index.js',        // 入口文件输出配置      output: {          path: __dirname,          filename: 'bundle.js' // filename和html里面的文件要对应      },      module: {          // 加载器配置          loaders: [{              test: /.js$/,              loader: 'babel-loader',              exclude: /node_modules/,              query: {                  presets: ['es2015']              }          }, {              test: /.tag$/,              loader: 'tag',              exclude: /node_modules/          }]      }  };

到这一步项目已经基本配置好了。我们可以写一个helloworld来试试

创建文件index.html

<!DOCTYPE html>  <html>    <head>      <meta charset="utf-8">      <title>RiotJS and Webpack</title>    </head>    <body>        <helloworld></helloworld>      <script src="bundle.js" charset="utf-8"></script>    </body>  </html>

这里的bundle.js和webpack.config.js里面的output.filename是对应的

新建src目录并创建文件index.js

var riot = require('riot');  var redux = require('redux');    // 引入helloworld.tag  require('./tags/helloworld.tag');    var reducer = function(state={      title: '欢迎进入Riot-Redux的世界!'  }, action) {      switch (action.type) {          case 'CHANGE_TITLE':              return Object.assign({}, state, {                  title: action.data              });              break;      }      return state;  };    var store = redux.createStore(reducer);    riot.mount('*', {      store  });

在src目录下创建tags目录并创建helloworld.tag

<helloworld>      <h1>{this.opts.store.getState().title}</h1>      <button type="button" name="button" onclick="{changeTitle}">变化</button>        <script>          changeTitle() {              this.opts.store.dispatch({type:'CHANGE_TITLE',data: ['星期一','星期二','星期三','星期四','星期五','星期六','星期日'][Math.floor(Math.random()*7)]});          }      </script>  </helloworld>

接下来使用命令启动项目

## 入口按上面的package.json里面配置了script,可以直接运行  npm run dev  ## 如果没有配置那就配置一下。

webpack-dev-server的默认端口是8080,所以直接访问http://localhost:8080 即可

修改代码不需要重启服务很方便

相关资料