1、externals
优势
项目中经常使用组件库 改成cdn方式引入 或者单独抽离出来引入
不用每个项目都引入 达到全局组件都可以使用共享
使用
首先在webpack.config.js 中使用externals 定义一个对象
这里的key表示引入import 的名称dom库 value表示引入组件全局变量名
2、cdn引入
externals:{
'react':"React",
'react-dom':"ReactDOM",
'Vue':'vue',
// 'lodash':'lodash',
// 'moment':'moment'
}
cdn引入
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>demo-react</title>
<script src="http://cdn.boot.com/lodash.js"></script>
<script src="http://cdn.boot.com/react.js"></script>
<script src="http://cdn.boot.com/react-dom.js"></script>
</head>
<body>
<div id="root"></div>
</body>
</html>
3、本地引入
externals:{
'react':"React",
'react-dom':"ReactDOM",
'Vue':'vue',
'lodash':'lodash',
// 'moment':'moment'
}
copy-webpack-plugin
使用copy-webpack-plugin 在webpack.config.js 中plugins配置里添加
new CopyWebpackPlugin([
{
from: path.resolve(__dirname,'static'),
to: path.resolve(__dirname,'dist/static')
},
{
from: path.resolve(__dirname,'dll/vendor.dll.js'),
to: path.resolve(__dirname,'dist')
},
{
from: path.resolve(__dirname,'./node_modules/react/umd/react.production.min.js'),
to: 'js/react.production.min.js'
},
{
from: path.resolve(__dirname,'./node_modules/react-dom/umd/react-dom.production.min.js'),
to: 'js/react-dom.production.min.js'
},
{
from: path.resolve(__dirname,'./node_modules/vue/dist/vue.min.js'),
to: 'js/vue.min.js'
},
]),
public/index.html引入
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>page-b</title>
<script src="js/react.production.min.js"></script>
<script src="js/react-dom.production.min.js"></script>
<script src="js/vue.min.js"></script>
</head>
<body>
<div id="root"></div>
</body>
</html>
项目使用
项目中这里无需引入react 入口文件已引入了全局react react-dom文件
import './index.scss';
// import React from 'react';
import { render } from 'react-dom';
// class Base extends Component {
// render () {
// return <div>test-base</div>
// }
// }
function Base () {
return <div>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
</div>
}
render(<Base/>,document.getElementById('root'));