首先抛出来我的目录结构
搭建的多入口环境,没有node中间层等等,用express和webpack启了一个服务,实现前端代码和后端代码的分离。
webpack.config.js webpack配置文件
util.js 工具文件
这两个文件用来配置webpack多入口环境
webpack.config.js
var path = require('path');
var utils = require('./utils.js');
const CleanWebpackPlugin = require('clean-webpack-plugin');
module.exports = {
mode: 'development',
devtool: 'inline-source-map',
devServer: {
contentBase: './dist'
},
entry: utils.getEntries('./src/modules/**/*.js'),
plugins: [
new CleanWebpackPlugin(['dist'])
].concat(utils.getHtmlPlugin('./src/modules/**/*.html')),
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js',
publicPath: '' //也会在服务器脚本用到,以确保文件资源能够在 http://localhost:3000 下正确访问
},
module: {
rules: [
{
test: /\.css$/,
use: [
'style-loader',
'css-loader'
]
},
{
test: /\.(eof|woff|woff2|ttf|svg)$/,
use: [
'file-loader'
]
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
{
loader:'url-loader',
options:{
limit:1,
outputPath:'images/'
}
}
]
},
{ test: /\.js$/,loader: "babel-loader" },
{
test: /\.art$/,
loader: "art-template-loader"
},
{
test: /\.html$/,
loader: 'html-url-loader'
}
]
}
};
util.js
var glob = require('glob');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const titles = [
'想要','我的'
]
exports.getEntries = function (globPath) {
var entries = {}
/**
* 读取src目录,并进行路径裁剪
*/
glob.sync(globPath).forEach(function (entry) {
var tmp = entry.split('/').splice(-3)
var moduleName = tmp.slice(1, 2);
var rep = new RegExp('(main\.js$)');
if(rep.test(entry)) {
entries[moduleName[0]+'/'+moduleName[0]] = entry
}
});
return entries;
}
exports.getHtmlPlugin = function(globPath){
var plugins = [], filename;
glob.sync(globPath).forEach(function (html,k) {
var tmp = html.split('/').splice(-3)
var moduleName = tmp.slice(1, 2);
if(moduleName[0]=="index"){
filename = 'index.html';
}else{
filename = moduleName+'/index.html'
}
plugins.push(new HtmlWebpackPlugin({
title: titles[k],
template:html,
filename:filename,
chunks:[moduleName[0]+'/'+moduleName[0]],
inject:'head'
}));
});
return plugins;
}
// favicon: 'path/to/my_favicon.ico'
用express创建服务
server.js
const express = require('express');
const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');
const app = express();
const config = require('./webpack.config.js');
const compiler = webpack(config);
// Tell express to use the webpack-dev-middleware and use the webpack.config.js
// configuration file as a base.
app.use(webpackDevMiddleware(compiler, {
publicPath: config.output.publicPath
}));
// Serve the files on port 3000.
app.listen(3000, function () {
console.log('Example app listening on port 3000!\n');
});
在package里面scripts里加入 node server.js
{
"name": "",
"version": "1.0.0",
"private": true,
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack",
"start": "webpack-dev-server --open",
"server": "node server.js"
},
......
}