1. 全局安裝webpack cnpm install --save-dev webpack 2. 初始化 cnpm init cnpm install --save-dev webpack 創建項目目錄( dist為生成目錄 ) 3. 配置文件 webpack.config.js 創建main.j ...
1. 全局安裝webpack
cnpm install --save-dev webpack
2. 初始化
cnpm init
cnpm install --save-dev webpack
創建項目目錄( dist為生成目錄 )
3. 配置文件 webpack.config.js
module.exports={ entry: __dirname+"/src/main.js", output: { path: __dirname+"/dist", filename: "bundle.js" } }
創建main.js文件
index.html 文件引入
<script src="dist/bundle.js"></script>
執行命令 webpack 即可生成list/bundle.js
4. babel配置
cnpm install --save-dev babel-core babel-loader babel-preset-es2015 babel-preset-react
webpack.config.js添加代碼:
module: { rules: [ { test: /(\.jsx|\.js)$/, use: { loader: "babel-loader", options: { presets: ["es2015","react"] } }, exclude: /node-modules/ }, ] },
測試:
src/js/a.js 代碼:
var obj={ a: 3, b: 2, add() { return this.a+this.b; } } export default obj;
main.js 引用:
import obj from "./js/a"; console.log(obj.add());
執行 webpack ,啟動瀏覽器查看
5. 構建伺服器
cnpm install --save-dev webpack-dev-server
配置:
devServer: { historyApiFallback: true, //不跳轉 inline: true //實時刷新 }
package.json中的 scripts 添加:
"start": "webpack", "server": "webpack-dev-server --open"
執行 npm start 生成bundle.js
執行 npm run server 啟動伺服器
修改index.html 文件引入路徑
<!-- bundle.js在虛擬記憶體中,可以實時刷新 --> <!-- dist/bundle.js是打包後才刷新 -->
<script src="bundle.js"></script>
6. css
cnpm install --save-dev style-loader css-loader
配置:
{ test: /\.css$/, use: [ { loader: "style-loader" }, { loader: "css-loader" } ] },
src/css/style.css 代碼:
html,body{ width: 100%; height: 100%; padding: 0; margin: 0; background-color: #ddd; }
main.js 引入:
import "./css/style.css";
7. sass
cnpm install --save-dev sass-loader
cnpm install node-sass
配置:
{ test: /\.scss$/, loader: 'style-loader!css-loader!sass-loader' },
src/scss/base.scss 代碼:
body{ div{ width: 200px; height: 200px; border: 1px solid #f69; margin: 20px auto; background: url("../images/1.png"); &:hover{ box-shadow: 0px 0px 5px 6px #aaa; } } }
main.js 引入:
import "./scss/base.scss";
8. image
cnpm install --save-dev url-loader
配置:
{ test: /(\.png|\.jpg)$/, loader: "url-loader?limit=8192" },
a: js 中的圖片引入
var imgUrl=require("./images/1.png");
b: html 中的圖片
<img src="./src/images/1.png" alt="">
c: css中的圖片
background: url("../images/1.png");
配置彙總:
module.exports={ entry: __dirname+"/src/main.js", output: { path: __dirname+"/dist", filename: "bundle.js" }, module: { rules: [ { test: /\.js$/, use: { loader: "babel-loader", options: { presets: ["es2015"] } }, exclude: /node-modules/ }, { test: /\.css$/, use: [ {loader: "style-loader"},{loader: "css-loader"} ] }, { test: /\.scss$/, loader: 'style-loader!css-loader!sass-loader' }, { test: /\.(png|jpg)$/, loader: 'url-loader?limit=8192' } ] }, devServer: { historyApiFallback: true,//不跳轉 inline: true//實時刷新 }, }