目录css
上节: webpack-dev-server上html
上节目录以下:webpack
以前devSerer的值是个空对象,用的都是默认配置,好比host:localhost, 端口:8080,这些均可以自定义
修改webpack.config.js:git
// 省略 devServer: { host: '0.0.0.0', port: 3306, hot: true }, // 省略
而后从新npm run dev, 这时既能够用localhost:3306,也能够用电脑ip:3306访问。es6
自从使用devServer后,便不像以前那样,每次都访问打包后的bundles目录下的代码,但其实output目录并不是不存在,而是在缓存中,只是没有写进磁盘,咱们仍是能够经过url访问到打包后的代码。
修改配置中output.filename属性
webpack.config.js:github
module.exports = { mode: 'production', entry: './src/index.js', output: { filename: '[name].js', path: resolve(__dirname, 'bundles') }, // 开启devServer devServer: { host: '0.0.0.0', port: 3306, hot: true }, module: { rules: [{ test: /\.(gif|jpg|jpeg|png|svg)$/, use: ['url-loader'] }, { test: /\.less$/, use: ['style-loader', 'css-loader', 'postcss-loader', 'less-loader'] }] }, plugins: [ new HtmlWebpackPlugin({ template: './index.html' }), new CleanWebpackPlugin(), new webpack.HotModuleReplacementPlugin() ] };
而后从新 npm run dev打开浏览器,应该和上节同样:web
这是输入网址:localhost:3306/main.js,应该能访问到打包后的main.js:npm
ps: 为何是main.js? 若是不急得了须要回顾下entry和output噢。
publicPath就是用来修改文件访问路径的,默认值是: '/'。
修改配置,webpack.config.js:segmentfault
devServer: { host: '0.0.0.0', port: 3306, hot: true, publicPath: '/assets/' },
从新 npm run dev, 这时的访问路径就变成了localhost:3306/assets/main.jsapi
当访问一个不存在路径好比:
若是想让全部的404请求的重定向到index.html,就须要配置historyApiFallback
webpack.config.js:
// 省略 devServer: { host: '0.0.0.0', port: 3306, hot: true, // publicPath: '/assets/' historyApiFallback: true }, // 省略
从新 npm run dev, 而后随便访问个不存在的路径都会重定向到index.html
还能够用正则作精确匹配,好比:
// 省略 devServer: { host: '0.0.0.0', port: 3306, hot: true, // publicPath: '/assets/' // historyApiFallback: true historyApiFallback: { rewrites: [ { from: /^\/$/, to: '/views/landing.html' }, // 根路径/ => /views/landing.html { from: /^\/subpage/, to: '/views/subpage.html' }, // /subpage => /views/subpage.html { from: /./, to: '/views/404.html' } ] } }, // 省略
利用devServer的proxy属性可轻松在开发阶段解决跨域问题
修改src/index.js:
// 请求接口 fetch('https://api-m.mtime.cn/Showtime/LocationMovies.api').then(res => { console.log('res :', res); });
而后npm run dev,打开f12 应该会看到典型的跨域错误:
修改配置,webpack.config.js:
// 省略 devServer: { host: '0.0.0.0', port: 3306, hot: true, // publicPath: '/assets/' historyApiFallback: true, proxy: { '/Showtime': { target: 'https://api-m.mtime.cn', changeOrigin: true } } }, // 省略
修改src/index.js:
fetch('/Showtime/LocationMovies.api').then(res => { console.log('res :', res); });
从新npm run dev, 就能请求到数据咯
proxy配置不少,还能够设置拦截器,好比:
// 省略 devServer: { host: '0.0.0.0', port: 3306, hot: true, // publicPath: '/assets/' historyApiFallback: true, proxy: { '/Showtime': { target: 'https://api-m.mtime.cn', changeOrigin: true } }, // 拦截器 bypass: function (req, res, proxyOptions) { if (req.headers.accept.indexOf("html") !== -1) { console.log("Skipping proxy for browser request."); return "/index.html"; } } }, // 省略
详细用法参考:https://github.com/chimurai/h...
下节:babel编译es6