$ mkdir test-loader
$ cd test-loader/
{
"name": "test-loader",
"version": "0.0.1",
"author": {
"name": "yanhao",
"email": "<yan5845hao@qq.com>"
},
"main": "index.js",
"scripts": {
"test": "webpack --progress --colors --config ./build/webpack.base.conf.js",
},
"license": "MIT",
"dependencies": {
},
"devDependencies": {
"webpack": "^2.4.1"
}
}
- 在项目中build下创建webpack.base.conf.js
var path = require('path');
module.exports = {
entry: './test/js/app.js',
output: {
path: path.resolve(__dirname, '../dist'),
filename: path.posix.join('','js/[name].[chunkhash].js'),
chunkFilename: path.posix.join('', 'js/[id].[chunkhash].js')
},
resolve:{
extensions: ['.vue','.js', '.json']
},
module: {
loaders: [
{ test: /\.vue$/, loader: '../test-loader' }
]
},
plugins: [
// 用来定义全局变量
new webpack.DefinePlugin({
'process.env': 'production'
}),
// js压缩工具
// 引入UglifyJsPlugin插件
// 最小化所有JavaScript输出块,消除无作用的代码。
new webpack.optimize.UglifyJsPlugin({
// 开启最小化模式,但是关闭警告功能
compress: {
warnings: false
}
}),
// 构建要编译输出的index.html,并在文件中嵌入资源文件
new HtmlWebpackPlugin({
// 文件路径
filename: path.resolve(__dirname, '../dist/index.html'),
// 模板文件 (index.html)
template: 'test/index.html',
// javascript 资源将被放置到 body 元素的底部
inject: true,
// 传递 html-minifier 选项给 minify 输出
minify: {
removeComments: true,// 去掉注释
collapseWhitespace: true, // 去掉空格
removeAttributeQuotes: true // 移除属性的引号
},
// 控制块在添加到页面之前的排序方式
// 通过CommonsChunkPlugin控制chunks在html文件中添加的顺序
// 设置为dependency即按照它们之间的依赖关系添加
chunksSortMode: 'dependency'
})
]
};
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test-loader</title>
</head>
<body>
<script src="js/main.js"></script>
<script>
console.log(uwo.UI);
</script>
</body>
</html>
<template>
<div>
<ul>
<li>1</li>
<li>2</li>
</ul>
</div>
</template>
var index = require('./index');
module.exports = window.uwo = index;
- 项目中创建index.js 这个是loader实现
module.exports = function (source) {
source = source.replace(/(\n)+|(\r\n)+|( )+/g, "");
return "module.exports = {'UI':'" + source + "'}";
}
npm run test
代码地址