一、使用node启动服务器,解决跨域问题(启动:node 文件路径)
需要安装node、express、http-proxy-middleware
const express = require('express');
const path = require('path');
const { exec } = require("child_process");
const proxyMiddleWare = require("http-proxy-middleware");// 用来处理跨域
const root = path.join(__dirname, './static');// 静态文件目录
const app = express();
// HOST:为目标服务器 POST:为启动服务端口
const { HOST = 'http://192.162.33.188', PORT = '3000' } = {};
// 配置代理设置项
const proxyOption = {
target: HOST,
changeOrigoin: true,
onProxyReq: function onProxyReq(proxyReq) {
proxyReq.setHeader('accessToken', '访问token');
}
};
app.set('port', PORT);
// 设置页面url
app.get('/notice', function (req, res) {
res.sendFile(path.resolve(__dirname, '../../error.html'));
});
// 设置根目录为静态资源
app.use('/', express.static(root));
// 使用反向代理
app.use("/api",proxyMiddleWare(proxyOption));
// 启动服务
app.listen(app.get('port'), () => {
let url = `http://localhost:${app.get('port')}`
// 自动打开默认浏览器
exec(`open ${url}`);
})
二、webpack压缩js,css(启动webpack --config webpack.config.js的配置路径)
需要安装node、webpack、extract-text-webpack-plugin、style-loader、css-loader、babel-loader、babel-preset-es2015。因为使用了babel-loader来告诉webpack如何加载js,还需要配置.babelrc文件。.babelrc文件内容可以是
const path = require('path');
const UglifyJSPlugin = require('webpack/lib/optimize/UglifyJsPlugin');// 压缩js
const ExtractTextPlugin = require('extract-text-webpack-plugin')// 压缩css
module.exports = {
entry: './index.js',// 入口js,从哪个js开始构建依赖关系图
output: {// 最终的js输入路径及js名字
path: path.resolve(__dirname, '../dist'),
filename: 'index.min.js'
},
module: {
rules: [{// webpack如何加载解析css文件
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: [{
loader: 'css-loader',
options: {
minimize: true
}
}]
})
},
{
test: /\.js$/,// 如何加载解析js
use: [{
loader: 'babel-loader',
options: {
presets: ['es2015']// 可以处理的js版本
}
}]
}]
},
plugins: [
// 压缩输出的 JS 代码
new UglifyJSPlugin({
compress: {
// 在UglifyJs删除没有用到的代码时不输出警告
warnings: false,
// 删除所有的 `console` 语句,可以兼容ie浏览器
drop_console: true,
// 内嵌定义了但是只用到一次的变量
collapse_vars: true,
// 提取出现多次但是没有定义成变量去引用的静态值
reduce_vars: true,
},
output: {
// 最紧凑的输出
beautify: false,
// 删除所有的注释
comments: false,
}
}),
new ExtractTextPlugin("index.min.css")// 输出的css名字
],
};