webpack的copy-webpack-plugin插件的作用是将项目中的某单个文件或整个文件夹在打包的时候复制一份到打包后的文件夹中(即复制一份到dist目录下)。
效果如下图所示:
使用方法:
给项目中添加copy-webpack-plugin
插件:
yarn add copy-webpack-plugin@5.1.2 --save
然后webpack.dev.js文件配置如下:
const CopyPlugin = require("copy-webpack-plugin"); plugins: [ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify(process.env.NODE_ENV), BUILD_ENV: JSON.stringify(process.env.BUILD_ENV) } }), new webpack.HotModuleReplacementPlugin(), new webpack.NoEmitOnErrorsPlugin(), // copy custom static assets new CopyPlugin( [ { from: path.resolve(__dirname, '../src/public/echarts.js'), to: path.resolve(__dirname, '../dist/static/js/echarts.js') }, { from: path.resolve(__dirname, '../src/public/china.js'), to: path.resolve(__dirname, '../dist/static/js/china.js') } ] ), ],
webpack.prod.js文件配置如下:
const CopyPlugin = require("copy-webpack-plugin"); plugins: [ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify(process.env.NODE_ENV), BUILD_ENV: JSON.stringify(process.env.BUILD_ENV), } }), new CleanWebpackPlugin(['dist'], { root: path.resolve(), }), new MiniCssExtractPlugin({ filename: 'static/css/[name]-[contenthash:8].css', chunkFilename: 'static/css/[name]-[contenthash:8].css', }), // copy custom static assets new CopyPlugin( [ { from: path.resolve(__dirname, '../src/public/echarts.js'), to: path.resolve(__dirname, '../dist/static/js/echarts.js') }, { from: path.resolve(__dirname, '../src/public/china.js'), to: path.resolve(__dirname, '../dist/static/js/china.js') } ] ), ]
关于copy-webpack-plugin
其他参数的配置可以查看copy-webpack-plugin