前面我们建立了一个项目, 现在我们在这个项目开始webpack学习
首先我们需要安装webpack,按照官网推荐安装方式,我们采用局部安装,进入static文件夹,运行安装命令:
npm init -y
npm install --save-dev webpack
安装后在stati目录下会生成一个package.json文件和一个node_modules文件夹
新建目录css、js、images和dist,并新建文件webpack.config.js
前面我们已经在页面上输出路hello world, 现在我们使用webpack输出hello world
在js文件夹下新建文件index.js,输入代码:
import _ from 'lodash';
function component(){
var element = document.createElement('div')
element.innerHTML = _.join(['hello', 'world'], ' ');
element.classList.add('hello');
return element;
}
document.body.appendChild(component())
在webpack.config.js中输入代码:
const path = require('path');
module.exports = {
entry: './js/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
}
};
在package.json的scripts中加入代码:
"build": "webpack"
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack"
},
回到templates目录,在在index.html中输入代码:
<html>
<head>
<title>Getting Started</title>
</head>
<body>
<script src="{{ url_for('static', filename='dist/bundle.js') }}"></script>
</body>
</html>
然后在node_modules目录下运行命令
npm run build
运行项目即可看到webpack输出的hello world
接下来为hello world添加样式
还是在node_modules目录下运行命令:
npm install --save-dev style-loader css-loader
安装好后修改webpack.config.js
在里面加入代码:
module: {
rules: [
{
test: /\.css$/,
use: [
'style-loader',
'css-loader'
]
}
]
}
既
const path = require('path');
module.exports = {
entry: './js/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
module: {
rules: [
{
test: /\.css$/,
use: [
'style-loader',
'css-loader'
]
}
]
}
};
在css目录下写下hello的样式,
.hello{....}
再次运行npm run build,hello就被添加上路样式