配置下环境先,记得➕‘--dev'的就是运行在开发模式的,在开发模式普通dependecies也能用
npm init
npm install //no need to npm install actually because we're in the initilization process.
npm install webpack --save-dev
npm install --save path
npm install react --save-dev
npm install react-dom --save-dev
npm install --save-dev babel-loader@6.2.1
npm install --save-dev babel-core@6.4.5
npm install --save-dev babel-preset-es2015@6.3.13
npm install --save-dev babel-preset-react@6.3.13
npm install --save-dev babel-preset-stage-2 //可以用上ES6的语法
npm install --save redux
npm install --save react-redux
npm install --save-dev redux-devtools
为了方便,加个webpack server
npm i webpack-dev-server
这就把环境配好了。。
webpack把静态资源文件称为模块,
我们设置下webpack:
var path = require('path');
var webpack = require('webpack');
module.exports = {
entry: { "page1" : "./entry.js", "page2" : [".entry2.js",".entry3.js"] }
output: {
path: __dirname, publicPath: "/output/"
filename: "[name].bundle.js"
},
resolve: {
extensions: ['', '.js', '.jsx'],
},
module: {
loaders: [
{ test: /\.css$/, loader: "style!css" },
{
test: /.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets:[ 'es2015', 'react', 'stage-2' ]
}
}
]
}
};
1 resolve:{ 2 extensions:['','.js','.json'] 3 }
entry定义了输入文件,可以是单个文件,也可以是数组。
output 定义了输出文件路径和名字 上面的结果就会输出为在当前目录下,有page1.bundle.js and page2.bundle.js
另外publicPath是网站运行时的访问路径
resolve是自动补全后缀: require('common')就会补全为require('common.js')
loader在module(模块)下面,所以说webpack把静态资源都称为模块。
那么webpack模块异步加载咋搞?
用它提供的require.ensure
require.ensure([
"jquery"
],
function
() {
//这里是异步的
console.log(
"进入require.ensure回调"
)
require(
"./ensure_a.js"
)
console.log(
"调用完require.ensure"
)
好像需要定义chunkFilename,这个再议。
output: {
path: path.join(__dirname,
"dist"
),
filename:
"[name].js"
,
publicPath:
"dist/"
,
//给require.ensure用
chunkFilename:
"[name].chunk.js"
//给require.ensure用
},
//页面引用的文件
我的package json:
{
"name": "todos",
"version": "1.0.0",
"description": "react redux todos",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "webpack-dev-server"
},
"author": "",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.4.5",
"babel-loader": "^6.2.1",
"babel-preset-es2015": "^6.3.13",
"babel-preset-react": "^6.3.13",
"babel-preset-stage-2": "^6.5.0",
"react": "^15.0.2",
"react-dom": "^15.0.2",
"redux-devtools": "^3.3.1",
"webpack": "^1.13.0",
"webpack-dev-server": "^1.14.1"
},
"dependencies": {
"path": "^0.12.7",
"react-redux": "^4.4.5",
"redux": "^3.5.2"
}
}