babel - 使用Webpack和Babel来搭建React应用程序
用Webpack(npm install -g webpack)代码打包,Webpack大致需要知道三件事: 1)让Webpack知道应用程序或js文件的根目录 具体来说,大致要做以下几件事情: 1)在项目根目录下有一个webpack.config.js文件,这个是惯例 module.exports = {};
3)告诉Webpack入口js文件在哪里 module.exports = { entry: ['./app/index.js'] } 4)告诉Webpack需要哪些转换插件 './app/index.js'],module: { loaders: [] } } 所有的转换插件放在loaders数组中。 5)设置转换插件的细节 module: { loaders: [ { test: /.coffee$/,include: __dirname + 'app',loader: "coffee-loader" } ] } }
6)告诉Webpack导出到哪里 "coffee-loader" } ] },output: { filename: "index_bundle.js",path: __dirname + '/dist' } } 【文件结构】 app/ 我们不禁要问,如何保证app/index.html和dist/index.html同步呢? 如果,我们每次运行webpack命令后,把app/index.html拷贝到dist/index.html中就好了。 解决这个问题的人是:html-webpack-plugin(npm install --save-dev html-webpack-plugin)。 引入html-webpack-plugin之后,webpack.config.js看起来是这样的: var HtmlWebpackPlugin = require('html-webpack-plugin');
var HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
template: __dirname + '/app/index.html',filename: 'index.html',inject: 'body'
});
'/dist'
},plugins: [HTMLWebpackPluginConfig]
}
【Webpack的一些指令】 webpack webpack -w //监测文件变化 webpack -p //不仅包括转换,还包括最小化文件 【Babel】 Babel可以用来把JSX文件转换成js文件。与Babel相关的安装包括: npm install --save-dev babel-core npm install --save-dev babel-loader npm install --save-dev babel-preset-react
在项目根文件夹下创建.babelrc文件。 {
"presets": ["react"]
}
把babel-loader放到webpack.config.js文件的设置中去。 module: {
loaders: [
{
test: /.js$/,21); line-height:1.8">"babel-loader"
}
]
},plugins: [HTMLWebpackPluginConfig]
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |