我正在将大型 RequireJS 应用程序迁移到 Webpack。使用 Webpack 的基本构建似乎工作正常——我已经将“路径”定义移动到“别名”,并且我已经为我的内容和垫片设置了加载器,比如 jQuery。
但是,还有一个问题,我不知道如何解决。基本上,RequireJS 应用程序使用“文本插件”来包含 HTML 模板,而 Webpack 会为 HTML 模板抛出“未找到模块”错误。
我要捆绑的示例 AMD 模块如下所示:
带有文本插件的 AMD 模块
define([
'security',
'modals',
'text!../templates/contact_info.html'
], function(security, modals, contactInfoTemplate) {
return {
foo: function() { return "bar"; }
};
});
我想我可以使用 raw-loader 来加载模板文件。我将“文本”别名为“原始加载器”:
text: {
test: /\.html$/,
loader: "raw-loader"
},
但是,对于上面所需的所有模板,我都看到以下错误:
Module not found: Error: Can't resolve 'text'
BREAKING CHANGE: It's no longer allowed to omit the '-loader' suffix when using loaders. You need to specify 'text-loader' instead of 'text'.
我尝试用'text-loader!...'替换'text!...',然后我看到这个错误,抱怨它无法加载/找到HTML模块!
Module not found: Error: Can't resolve '../templates/contact_info.html'
webpack.config.js,版本 3.9.1
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const path = require('path');
const webpack = require('webpack');
let basePath = path.join(__dirname, '/');
module.exports = {
entry: {
'main': basePath + 'js/main.js',
},
context: __dirname,
output: {
path: __dirname + '/build',
filename: '[name].min.js',
libraryTarget: 'amd',
umdNamedDefine: true
},
module: {
rules: [
{
test: /(\.js)$/,
exclude: /(node_modules)/,
use: {
// babel-loader to convert ES6 code to ES5 + amdCleaning requirejs code into simple JS code, taking care of modules to load as desired
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env'],
plugins: []
}
}
},
{
test: /\.css$/,
use: [
{ loader: "style-loader" },
{ loader: "css-loader" }
]
},
{ test: /\.jpg$/, use: [ "file-loader" ] },
{ test: /\.png$/, use: [ "url-loader?mimetype=image/png" ] },
{
test: /\.(html)$/,
use: {
loader: 'raw-loader',
options: {
minimize: true
}
}
}
]
},
resolve: {
modules: [
'js/**/*.js',
'node_modules',
path.resolve('./js')
],
extensions: ['.js'], // File types,
alias: {
text: {
test: /\.html$/,
loader: "raw-loader"
},
bridge: 'libs/bridge',
cache: 'libs/cache',
cards: 'libs/cards',
moment: 'libs/moment',
underscore: 'libs/underscore',
}
},
plugins: [
new CleanWebpackPlugin(['dist']),
new HtmlWebpackPlugin({
filename: 'index.html',
template: '../index.html'
}),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery'
})
]
};
任何人都知道如何让 Webpack 与 RequireJS Text 插件很好地配合使用?
谢谢!