我正在尝试使用 webpack 的 dllPlugin 来缩小我的块,我让它在客户端运行良好,但在服务器端渲染中出现问题。
我以此为例,并使其更简单,这是我的演示代码:
webpack.config.dll.js
// webpack.config.dll.js
const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: {
a: ['./a']
},
output: {
path: path.join(__dirname, 'dist'),
filename: '[name].js',
library: '[name]'
},
plugins: [
new webpack.DllPlugin({
path: path.join(__dirname, 'dist', 'manifest.json'),
name: '[name]'
})
]
}
webpack.config.js
// webpack.config.js
const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: './example',
output: {
path: path.join(__dirname, 'dist'),
filename: 'output.js'
},
plugins: [
new webpack.DllReferencePlugin({
context: __dirname,
manifest: require('./dist/manifest.json')
})
]
};
其他js代码和html代码是
// a.js
module.exports = 'a';
// example.js
console.log(require("./a"));
// index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<script src="dist/a.js"></script>
<script src="dist/output.js"></script>
</body>
</html>
如果我在浏览器中打开 index.html,它运行良好并在控制台中输出“a”。但如果我执行node dist/output.js
,它会得到错误:
/WorkSpace/code/webpack/005_dllPluginDemo_20160813/dist/output.js:64
module.exports = a;
^
ReferenceError: a is not defined
at Object.<anonymous> (/WorkSpace/code/webpack/005_dllPluginDemo_20160813/dist/output.js:64:19)
at __webpack_require__ (/WorkSpace/code/webpack/005_dllPluginDemo_20160813/dist/output.js:20:30)
at Object.module.exports (/WorkSpace/code/webpack/005_dllPluginDemo_20160813/dist/output.js:58:20)
at __webpack_require__ (/WorkSpace/code/webpack/005_dllPluginDemo_20160813/dist/output.js:20:30)
at Object.<anonymous> (/WorkSpace/code/webpack/005_dllPluginDemo_20160813/dist/output.js:48:14)
at __webpack_require__ (/WorkSpace/code/webpack/005_dllPluginDemo_20160813/dist/output.js:20:30)
at /WorkSpace/code/webpack/005_dllPluginDemo_20160813/dist/output.js:40:18
at Object.<anonymous> (/WorkSpace/code/webpack/005_dllPluginDemo_20160813/dist/output.js:43:10)
at Module._compile (module.js:413:34)
at Object.Module._extensions..js (module.js:422:10)
所以这意味着我的代码中不能要求 output.js。不幸的是,当我尝试在服务器中渲染时,我需要这样做,就像这个样板一样
我认为问题在于模块 a 已经被 webpack 处理了两次
那么有人遇到过这个问题吗?你是怎么解决的,希望你的回答,谢谢