原文链接: nodejs 环境配置 webpack 安装及入门
上一篇: js 时间库 moment
下一篇: js 基础
node安装vue-cli,配置vue开发环境和web
下载node
全局安装cnpm和webpack
npm install -g cnpm --registry=https://registry.npm.taobao.org
cnpm install webpack -g
第一个项目结构
index.html
使用构建后的js文件
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>test</title>
</head>
<body>
hello webpack
<script src="main.bundle.js" charset="utf-8"></script>
</body>
</html>
one.js
导出模块
function one() {
console.log("one,一")
}
module.exports = one;
在main中 使用
先导入,在使用
import one from "./one"
import two from "./two"
import three from "./three"
one()
two()
three()
构建
webpack main.js main.bundle.js
浏览器查看效果
使用配置文件,项目结构
webpack.config.js 是项目的配置文件,指定入口和出口
const path = require('path');
module.exports = {
entry: './src/main.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'main.bundle.js'
}
};
执行webpack即可成功构建
配置文件也可以更加复杂,可以进行其他配置
const path = require('path');
const config = {
entry: './src/main.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'main.bundle.js'
},
module: {
rules: [
]
}
};
module.exports = config;
配置可以打包css文件
使用css-loader加载css文件
安装
cnpm install --save-dev css-loader -g
配置,设置对所有的css文件使用css-loader 加载
注意,json 数组的末尾没有逗号!!!!!!!!!!!!!!
const path = require('path');
const config = {
entry: './src/main.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'main.bundle.js'
},
module: {
rules: [
{ test: /\.css$/, use: 'css-loader' }
]
}
};
module.exports = config;
引用直接引用即可
使用插件混淆代码
cnpm install webpack --save-dev
在配置文件中使用插件 new webpack.optimize.UglifyJsPlugin() 即可
const webpack = require('webpack'); //访问内置的插件
const path = require('path');
const config = {
entry: './src/main.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'main.bundle.js'
},
module: {
rules: [{
test: /\.css$/,
use: 'css-loader'
}]
},
plugins: [
new webpack.optimize.UglifyJsPlugin()
]
};
module.exports = config;